import { cookies } from "next/headers";
import { redirect } from "next/navigation";

/**
 * Server-side logout function that clears NextAuth cookies
 * and redirects to login page
 */
export async function serverLogout(): Promise<never> {
  const cookieStore = await cookies();

  // Get all cookies to find auth-related ones
  const allCookies = cookieStore.getAll();

  // Clear NextAuth session cookies (try all possible patterns)
  const cookieNamesToDelete = [
    "next-auth.session-token",
    "next-auth.csrf-token",
    "next-auth.callback-url",
    "__Secure-next-auth.session-token",
    "__Secure-next-auth.csrf-token",
    "__Secure-next-auth.callback-url",
  ];

  // Delete known patterns
  cookieNamesToDelete.forEach(name => {
    cookieStore.delete(name);
  });

  // Also delete any cookies that contain "next-auth" in their name
  allCookies.forEach(cookie => {
    if (cookie.name.includes("next-auth") || cookie.name.includes("nextauth")) {
      cookieStore.delete(cookie.name);
    }
  });

  // Redirect to login with a timestamp to prevent caching
  redirect("/login?loggedout=true&ts=" + Date.now());
}
