import { oauth2IdpInitiated } from 'src/services/authService';
import { IDP_PROVIDER_PROTOCOL, type IdpProvider } from 'src/types/login';
import { generateCodeChallenge, generateCodeVerifier } from 'src/utils/pkce';

export const launchIdpProvider = async (app: IdpProvider): Promise<void> => {
  if (app.protocol !== IDP_PROVIDER_PROTOCOL.OAUTH) {
    throw new Error('SAML flow handled by legacy mutation');
  }

  if (!app.audienceIdentifier || !app.redirectUri) {
    throw new Error(`OAuth provider ${app.id} missing required fields`);
  }

  const codeVerifier = generateCodeVerifier();
  const codeChallenge = await generateCodeChallenge(codeVerifier);

  const { data } = await oauth2IdpInitiated({
    ...(app.clientId && { clientId: app.clientId }),
    audienceIdentifier: app.audienceIdentifier,
    codeChallenge,
    codeChallengeMethod: 'S256',
    redirectUri: app.redirectUri,
  });

  const launchUrl = `${data.redirectUri}?code=${encodeURIComponent(
    data.code,
  )}&code_verifier=${encodeURIComponent(codeVerifier)}`;

  window.open(launchUrl, '_blank', 'noopener,noreferrer');
};
