'use server';

import { cookies } from 'next/headers';

export async function clearAuthCookies() {
  const cookieStore = await cookies();

  // Delete all next-auth v5 cookie variants
  // Must specify path and secure options to match how they were set
  const cookieNames = [
    'authjs.session-token',
    'authjs.csrf-token',
    'authjs.callback-url',
    '__Secure-authjs.session-token',
    '__Secure-authjs.csrf-token',
    '__Secure-authjs.callback-url',
    // next-auth v4 fallback names
    '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',
    // Host-prefixed variants (used when behind a proxy)
    '__Host-authjs.csrf-token',
    '__Host-next-auth.csrf-token',
  ];

  for (const name of cookieNames) {
    // Delete with explicit options to ensure cookie is actually removed
    cookieStore.delete({
      name,
      path: '/',
    });
  }

  // Also try getting all cookies and deleting any auth-related ones
  const allCookies = cookieStore.getAll();
  for (const cookie of allCookies) {
    if (
      cookie.name.includes('authjs') ||
      cookie.name.includes('next-auth') ||
      cookie.name.includes('session-token')
    ) {
      cookieStore.delete({ name: cookie.name, path: '/' });
    }
  }

  return { success: true };
}
