import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";

function purgeOrgCookies(res: NextResponse) {
  try {
    res.cookies.set("active_org_id", "", { path: "/", maxAge: 0 });
    res.cookies.set("active_org_id", "", { path: "/staff", maxAge: 0 });
  } catch {}
}

function purgeSupabaseCookies(res: NextResponse) {
  try {
    const reqCookies = cookies().getAll();
    for (const c of reqCookies) {
      if (c.name.startsWith("sb-") || c.name.startsWith("supabase")) {
        res.cookies.set(c.name, "", { path: "/", maxAge: 0 });
      }
    }
  } catch {}
}

async function handleSignOut(request: Request, asRedirect: boolean) {
  const supabase = createRouteHandlerClient({ cookies });
  await supabase.auth.signOut();

  const nextUrl = new URL("/signin", request.url); // destination par défaut après déconnexion

  if (asRedirect) {
    const res = NextResponse.redirect(nextUrl);
    purgeOrgCookies(res);
    purgeSupabaseCookies(res);
    return res;
  }

  const res = NextResponse.json({ ok: true });
  purgeOrgCookies(res);
  purgeSupabaseCookies(res);
  return res;
}

export async function GET(request: Request) {
  // Navigation directe (Link, visite d'URL) → redirect
  return handleSignOut(request, true);
}

export async function POST(request: Request) {
  // Si c'est un fetch/XHR, on renvoie JSON ; sinon redirect
  const accept = request.headers.get("accept") || "";
  const xrw = request.headers.get("x-requested-with") || "";
  const asRedirect = !(accept.includes("application/json") || xrw === "XMLHttpRequest");
  return handleSignOut(request, asRedirect);
}
