/**
 * `POST /social-auth/` is both the login and the register endpoint: it issues a
 * token for a known email and creates the account for an unknown one. What it
 * will not do is create a half-account — a brand-new volunteer must arrive with
 * the identifier required by their nationality/residency selection (civil ID or
 * passport), and a brand-new organization with its company details — so the
 * sign-up screens ask `POST /check-user/` first and send anyone new through the
 * matching onboarding screen before the single social-auth call.
 *
 * Two payloads ride along in sessionStorage between those screens:
 *   `oauth_user`  — the provider profile (email, names, provider id, picture)
 *   **and `social_token`**, the provider credential the backend verifies.
 *   `social_signup_prefill` — whatever the visitor had already typed into the
 *   registration form before clicking Google / LinkedIn, so the onboarding
 *   screen does not make them type it a second time. LinkedIn leaves the page
 *   entirely, so this has to survive a full reload, not just a `router.push`.
 */

export const OAUTH_USER_KEY = "oauth_user";
const SOCIAL_PREFILL_KEY = "social_signup_prefill";

export interface SocialProfile {
  email: string;
  first_name?: string;
  last_name?: string;
  social_media_id?: string;
  /* `AuthController::socialAuth()` validates this with
     `Rule::in(['google', 'linkedin'])`, so it is not a free string. */
  social_media_provider: "google" | "linkedin";
  social_profile_pic_url?: string;
  /**
   * BE-160 — the only thing `POST /social-auth/` takes identity from; `email`
   * and `social_media_id` are sent but ignored. Google: the Identity Services
   * **ID token** (JWT `credential`, ~1 h). LinkedIn: the signed ticket
   * `/linkedin/callback/` returns (~600 s). It rides in the stash so the
   * second `/social-auth/` call, made after the onboarding screen, carries it
   * too; an expired one answers 401 — see `isSocialCredentialRejected`.
   */
  social_token: string;
}

export type SocialUserType = "volunteer" | "organization";

interface StoredPrefill {
  user_type: SocialUserType;
  values: Record<string, unknown>;
}

/** Where a brand-new account of this type finishes signing up. */
export function socialOnboardingRoute(userType: SocialUserType): string {
  return userType === "organization"
    ? "/complete-details"
    : "/volunteer-mandate-details";
}

export function stashSocialProfile(profile: SocialProfile): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.setItem(OAUTH_USER_KEY, JSON.stringify(profile));
  } catch {
    // Private mode / quota — the onboarding screen just starts empty.
  }
}

/**
 * Drop the empty fields before stashing: a blank prefill value would otherwise
 * count as "already answered" and blank out a field the provider could fill.
 */
export function setSocialPrefill(
  userType: SocialUserType,
  values: Record<string, unknown>
): void {
  if (typeof window === "undefined") return;
  const filled: Record<string, unknown> = {};
  for (const [field, value] of Object.entries(values)) {
    if (value === "" || value === null || value === undefined) continue;
    filled[field] = value;
  }

  try {
    if (Object.keys(filled).length === 0) {
      sessionStorage.removeItem(SOCIAL_PREFILL_KEY);
      return;
    }
    const payload: StoredPrefill = { user_type: userType, values: filled };
    sessionStorage.setItem(SOCIAL_PREFILL_KEY, JSON.stringify(payload));
  } catch {
    // ignore
  }
}

/**
 * Read the prefill once and drop it, so a flow that was abandoned halfway
 * cannot repopulate an unrelated sign-up later in the same tab. Returns null
 * when the stash belongs to the other account type.
 *
 * Three cases, and the order of the delete is what separates them:
 *
 *  - **mine** — consumed and returned. The delete is what makes this hook
 *    safe to call from a mount effect that StrictMode runs twice: the second
 *    pass finds nothing, and the caller keeps what the first pass read.
 *  - **unreadable** — consumed and `null`. A half-written entry has to be
 *    cleared or it poisons the key for the rest of the tab.
 *  - **the other account type** — **left in place**. This used to delete
 *    first and check the type afterwards, so an organization screen reading
 *    the key destroyed a volunteer's answers. Nothing co-mounts the two
 *    consumers today — they are on separate routes — so it was latent rather
 *    than live, but deleting another flow's payload is never the right
 *    reading of "consume mine". Note that leaving it does not weaken the
 *    guarantee above: the entry records its own `user_type`, so it can only
 *    ever be returned to a sign-up of that same type.
 */
export function takeSocialPrefill(
  userType: SocialUserType
): Record<string, unknown> | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = sessionStorage.getItem(SOCIAL_PREFILL_KEY);
    if (!raw) return null;

    let stored: StoredPrefill | null = null;
    try {
      stored = JSON.parse(raw) as StoredPrefill;
    } catch {
      sessionStorage.removeItem(SOCIAL_PREFILL_KEY);
      return null;
    }

    if (!stored || stored.user_type !== userType) return null;
    sessionStorage.removeItem(SOCIAL_PREFILL_KEY);
    return stored.values ?? null;
  } catch {
    return null;
  }
}

export function clearSocialSignupState(): void {
  if (typeof window === "undefined") return;
  try {
    sessionStorage.removeItem(OAUTH_USER_KEY);
    sessionStorage.removeItem(SOCIAL_PREFILL_KEY);
  } catch {
    // ignore
  }
}

/** Overlay the stashed answers onto a form's defaults, ignoring unknown fields. */
export function applyPrefill<T extends Record<string, unknown>>(
  defaults: T,
  prefill: Record<string, unknown> | null
): T {
  if (!prefill) return defaults;
  const merged: Record<string, unknown> = { ...defaults };
  for (const [field, value] of Object.entries(prefill)) {
    if (!(field in defaults)) continue;
    merged[field] = value;
  }
  return merged as T;
}

/**
 * The stashed provider profile, or `null`.
 *
 * Browser-only and total: a missing key, a quota/private-mode throw and a
 * half-written entry all answer `null`, because every caller's fallback is the
 * same — show the onboarding form with its fields empty.
 *
 * It does **not** consume the entry. `clearSocialSignupState()` is what drops
 * it, once the social-auth call has succeeded, and several screens read the
 * profile more than once before that happens.
 */
export function readStashedSocialProfile<T = SocialProfile>(): T | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = sessionStorage.getItem(OAUTH_USER_KEY);
    return raw ? (JSON.parse(raw) as T) : null;
  } catch {
    return null;
  }
}

/**
 * `/social-auth/` answered 401: the `social_token` is forged, malformed or —
 * the realistic case — expired (a LinkedIn ticket lives ~600 s, a Google ID
 * token ~1 h). Nothing on the onboarding screen can fix that; the visitor has
 * to sign in with the provider again. 503 ("provider unreachable") is not this:
 * it is retryable as is, and its `msg` says so.
 */
export function isSocialCredentialRejected(error: unknown): boolean {
  if (!error || typeof error !== "object") return false;
  const { response } = error as {
    response?: { status?: number; data?: { code?: number } };
  };
  return response?.status === 401 || response?.data?.code === 401;
}
