import { NextResponse } from "next/server";
import { safeLoginCallbackPath } from "@/lib/utils/safe-redirect";

const SESSION_COOKIES = [
  "next-auth.session-token",
  "__Secure-next-auth.session-token",
  "next-auth.callback-url",
  "__Secure-next-auth.callback-url",
  "next-auth.csrf-token",
  "__Host-next-auth.csrf-token",
  "__Secure-next-auth.csrf-token",
  "next-auth.pkce.code_verifier",
  "__Secure-next-auth.pkce.code_verifier",
];

/**
 * Clears NextAuth cookies then redirects to /login only.
 * Used when a JWT is still present but the account/workspace is invalid.
 */
export async function GET(request: Request) {
  const url = new URL(request.url);
  const dest = safeLoginCallbackPath(url.searchParams.get("callbackUrl"));
  const res = NextResponse.redirect(new URL(dest, url.origin));
  const secure = url.protocol === "https:";

  for (const name of SESSION_COOKIES) {
    res.cookies.set(name, "", {
      httpOnly: true,
      path: "/",
      maxAge: 0,
      expires: new Date(0),
      sameSite: "lax",
      secure,
    });
  }

  res.headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
  res.headers.set("Clear-Site-Data", '"cookies"');

  return res;
}
