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

const ADMIN_USERNAME = 'admin';
const ADMIN_PASSWORD = 'admin.3434';

export async function POST(request: NextRequest) {
  try {
    const { username, password } = await request.json();

    if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) {
      const cookieStore = await cookies();
      const hostname = request.headers.get("host") || "";
      
      // Extract root domain for cookie (e.g., "admin.example.com" -> ".example.com")
      // This allows cookies to work across subdomains
      let cookieDomain: string | undefined;
      if (hostname.includes(".")) {
        const parts = hostname.split(".");
        if (parts.length >= 2) {
          // Get root domain (last two parts, e.g., "example.com")
          const rootDomain = parts.slice(-2).join(".");
          cookieDomain = `.${rootDomain}`;
        }
      }
      
      const cookieOptions: any = {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict' as const,
        maxAge: 60 * 60 * 24, // 24 hours
      };
      
      // 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', 'authenticated', cookieOptions);

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

    return NextResponse.json(
      { success: false, error: 'Invalid credentials' },
      { 
        status: 401,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Invalid request' },
      { 
        status: 400,
        headers: {
          'Cache-Control': 'no-store, no-cache, must-revalidate, private',
        },
      }
    );
  }
}

