/**
 * SSO helpers for Google / Microsoft OAuth (#24).
 * Start URLs hit the backend, which redirects to the IdP.
 */

/**
 * Absolute backend OAuth start URL.
 * @param {'google'|'microsoft'} provider
 * @param {'login'|'signup'|'link_drive'|'link_company_drive'} intent
 * @returns {string}
 */
export function oauthStartUrl(provider, intent = 'login') {
  const base = (process.env.REACT_APP_BACKEND_REST_API_BASE_URL || '').replace(/\/?$/, '/');
  const params = new URLSearchParams({ intent });
  return `${base}auth/oauth/${provider}/start/?${params.toString()}`;
}

/**
 * Begin browser redirect to IdP via backend.
 * @param {'google'|'microsoft'} provider
 * @param {'login'|'signup'|'link_drive'|'link_company_drive'} intent
 */
export function startOAuth(provider, intent = 'login') {
  window.location.assign(oauthStartUrl(provider, intent));
}

const ERROR_MESSAGES = {
  access_denied: 'Sign-in was cancelled.',
  email_missing: 'Your account with this provider has no email address.',
  email_unverified: 'Your email with this provider is not verified.',
  link_conflict: 'This email is already linked to a different identity for this provider.',
  account_not_found: 'No account exists for this email. Contact your administrator or sign up.',
  registration_disabled: 'Account registration is currently disabled.',
  provider_not_configured: 'This sign-in method is not available.',
  invalid_state: 'Sign-in session expired. Please try again.',
  missing_code: 'Sign-in did not complete. Please try again.',
  token_exchange_failed: 'Could not complete sign-in with the provider. Try again.',
  profile_fetch_failed: 'Could not load your profile from the provider.',
  profile_incomplete: 'Provider profile was incomplete. Try again.',
  provider_error: 'The identity provider returned an error.',
  server_error: 'Unexpected sign-in error. Try again.',
  invalid_provider: 'Unsupported sign-in provider.',
};

/**
 * @param {string|null|undefined} code
 * @param {string|null|undefined} description
 * @returns {string}
 */
export function oauthErrorMessage(code, description) {
  if (code && ERROR_MESSAGES[code]) {
    return ERROR_MESSAGES[code];
  }
  if (description) {
    return String(description);
  }
  return 'Could not complete sign-in. Try again.';
}
