import type { SocialProfile } from "@/lib/auth/socialSignup";

/**
 * Google sign-in, as `POST /social-auth/` now needs it (BE-160).
 *
 * The backend verifies a Google **ID token** — the JWT `credential` that
 * Google Identity Services hands `<GoogleLogin>` — against our client id
 * (`aud`), issuer and `email_verified`. The OAuth access token the old
 * `useGoogleLogin` implicit flow produced cannot be verified that way and is
 * rejected with a 401, so the button is GIS's own (see `SocialAuthButtons`).
 *
 * The profile fields the screens need before the backend is asked anything —
 * the email for `POST /check-user/`, the names that prefill the onboarding
 * form — are read straight out of the token's payload instead of calling
 * Google's `userinfo`. They are **display data only**: the payload is decoded,
 * not verified, here. The backend re-derives the identity from the token and
 * ignores `email` / `social_media_id` in the body.
 */

interface GoogleIdTokenClaims {
  sub?: string;
  email?: string;
  given_name?: string;
  family_name?: string;
  picture?: string;
}

/** base64url → UTF-8 text. Names arrive in Arabic, so not a bare `atob`. */
function decodeBase64Url(segment: string): string {
  const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
  const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
  const binary = atob(padded);
  const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

/**
 * The stashable profile for a Google sign-in, from the GIS `credential`, or
 * `null` when it is not a readable JWT carrying an email.
 */
export function socialProfileFromGoogleCredential(
  credential: string | undefined | null
): SocialProfile | null {
  if (!credential) return null;
  const payloadSegment = credential.split(".")[1];
  if (!payloadSegment) return null;

  let claims: GoogleIdTokenClaims;
  try {
    claims = JSON.parse(decodeBase64Url(payloadSegment)) as GoogleIdTokenClaims;
  } catch {
    return null;
  }
  if (!claims || typeof claims.email !== "string" || !claims.email) return null;

  return {
    email: claims.email,
    first_name: claims.given_name || undefined,
    last_name: claims.family_name || undefined,
    social_media_id: claims.sub || undefined,
    social_media_provider: "google",
    social_profile_pic_url: claims.picture || undefined,
    social_token: credential,
  };
}
