import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';

export async function POST(request: NextRequest) {
  const cookieStore = await cookies();
  const hostname = request.headers.get("host") || "";
  
  // Extract root domain for cookie (e.g., "admin.example.com" -> ".example.com")
  let cookieDomain: string | undefined;
  if (hostname.includes(".")) {
    const parts = hostname.split(".");
    if (parts.length >= 2) {
      const rootDomain = parts.slice(-2).join(".");
      cookieDomain = `.${rootDomain}`;
    }
  }
  
  const cookieOptions: any = {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict' as const,
  };
  
  // Only set domain in production or if explicitly configured
  if (cookieDomain && (process.env.NODE_ENV === 'production' || process.env.ALLOW_SUBDOMAIN_COOKIES === 'true')) {
    cookieOptions.domain = cookieDomain;
  }
  
  cookieStore.set('admin-auth', '', {
    ...cookieOptions,
    maxAge: 0, // Expire immediately
  });

  return NextResponse.json(
    { success: true },
    {
      headers: {
        'Cache-Control': 'no-store, no-cache, must-revalidate, private',
      },
    }
  );
}

