/**
 * POST /api/auth/signout-all
 *
 * Unified sign-out that clears every auth session type used in Mawidi:
 *   - NextAuth JWT session (next-auth.session-token / authjs.session-token)
 *   - Custom auth_token (used by OTP + Google OAuth flow in lib/auth.ts)
 *   - Staff JWT session (staff-session from lib/staff-session.ts)
 *   - CSRF token
 *   - Clerk session (revoked server-side via clerkClient + cookie expiry)
 *
 * No CSRF requirement — sign-out is always safe to invoke (clearing sessions
 * cannot cause harm, and the caller may only have a Clerk session with no CSRF token).
 */

import { NextResponse } from "next/server";
import { logger } from "@/lib/logger";

/**
 * All auth-related cookies that must be expired on sign-out.
 * Includes both the plain-HTTP variants (dev) and the Secure/Host-prefix
 * variants (production HTTPS).
 */
const ALL_AUTH_COOKIES = [
  // NextAuth v5 — legacy names
  "next-auth.session-token",
  "__Secure-next-auth.session-token",
  "next-auth.csrf-token",
  "__Host-next-auth.csrf-token",
  "next-auth.callback-url",
  // NextAuth v5 — new authjs.* names (some builds use these)
  "authjs.session-token",
  "__Secure-authjs.session-token",
  "authjs.csrf-token",
  "__Host-authjs.csrf-token",
  "authjs.callback-url",
  // Custom Mawidi tokens
  "auth_token",
  "staff-session",
  "csrf-token",
  // Clerk cookies
  "__clerk_db_jwt",
  "__client_uat",
  "__session",
  "__clerk_handshake",
] as const;

export async function POST() {
  // 1. Revoke Clerk session server-side (backend API) if Clerk is configured.
  //    This invalidates the session token at the Clerk network level, not just
  //    in the browser cookie — preventing re-use of a captured token.
  if (process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY) {
    try {
      const { auth, clerkClient } = await import("@clerk/nextjs/server");
      const { sessionId } = await auth();
      if (sessionId) {
        const client = await clerkClient();
        await client.sessions.revokeSession(sessionId);
        logger.info("Clerk session revoked on signout-all", { sessionId });
      }
    } catch (err) {
      // Clerk not active, or session already expired — skip silently.
      logger.warn("Clerk session revocation skipped during signout-all", {
        error: String(err),
      });
    }
  }

  // 2. Build the response and expire every auth cookie.
  //    Setting maxAge: 0 causes the browser to immediately delete the cookie.
  const response = NextResponse.json({ success: true });

  for (const name of ALL_AUTH_COOKIES) {
    response.cookies.set(name, "", { maxAge: 0, path: "/" });
  }

  return response;
}
