'use server';

import { cookies } from 'next/headers';

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

  // All possible NextAuth cookie names (v4 + v5, secure + host prefixed)
  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.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-authjs.csrf-token',
    '__Host-next-auth.csrf-token',
  ];

  // Aggressively expire each cookie by setting empty value + maxAge: 0
  // This works better than .delete() in production behind load balancers
  for (const name of cookieNames) {
    try {
      cookieStore.set({
        name,
        value: '',
        path: '/',
        maxAge: 0,
        httpOnly: true,
        secure: true,
        sameSite: 'lax',
      });
    } catch {
      // Some Secure cookies cannot be set in non-HTTPS environments
    }
    // Also try non-secure version
    try {
      cookieStore.set({
        name,
        value: '',
        path: '/',
        maxAge: 0,
      });
    } catch {
      // ignore
    }
  }

  // Sweep: any remaining cookies that look auth-related → expire them
  const allCookies = cookieStore.getAll();
  for (const cookie of allCookies) {
    if (
      cookie.name.includes('authjs') ||
      cookie.name.includes('next-auth') ||
      cookie.name.includes('session-token')
    ) {
      try {
        cookieStore.set({
          name: cookie.name,
          value: '',
          path: '/',
          maxAge: 0,
          httpOnly: true,
          secure: true,
          sameSite: 'lax',
        });
      } catch {
        // ignore
      }
      try {
        cookieStore.set({ name: cookie.name, value: '', path: '/', maxAge: 0 });
      } catch {
        // ignore
      }
    }
  }

  return { success: true };
}
