/**
 * Unified client-side sign-out helper.
 *
 * Clears ALL active session types (NextAuth, auth_token, staff-session, Clerk)
 * by calling /api/auth/signout-all on the server, then optionally triggering
 * Clerk's client-side signOut to flush any in-memory state, and finally
 * performing a hard redirect so all React/context state is discarded.
 *
 * Safe to call regardless of which auth provider is currently active.
 */

/**
 * Sign out of all active sessions and redirect to `redirectTo`.
 *
 * @param redirectTo  Destination URL after sign-out (default: /en/clerk-login)
 */
export async function signOutAll(redirectTo = "/en/clerk-login"): Promise<void> {
  // 1. Ask the server to revoke Clerk session + expire all auth cookies.
  try {
    await fetch("/api/auth/signout-all", {
      method: "POST",
      credentials: "include", // ensures session cookies are sent
    });
  } catch {
    // Best-effort — if the network call fails we still clear client state
    // and redirect.  The session will expire naturally on the server.
  }

  // 2. Flush Clerk's in-memory client state if the Clerk JS SDK is loaded.
  //    The ClerkJS singleton attaches itself to `window.Clerk` when it loads.
  //    We call signOut() here purely to clear any cached tokens held in memory
  //    by Clerk's client SDK — the server already revoked the session in step 1.
  if (typeof window !== "undefined") {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const clerkGlobal = (window as any).Clerk;
      if (typeof clerkGlobal?.signOut === "function") {
        await clerkGlobal.signOut();
      }
    } catch {
      // Clerk SDK not loaded or signOut failed — ignore.
    }
  }

  // 3. Hard-navigate to clear all React/context state in memory.
  if (typeof window !== "undefined") {
    window.location.href = redirectTo;
  }
}
