// src/pages/api/auth/login.ts 
import type { APIRoute } from 'astro';
import { generateAuthUrl, generateState, logAuthEvent } from '../../../utils/auth.js';
import { serialize } from 'cookie';

export const prerender = false;

export const GET: APIRoute = async ({ url, redirect }) => {
  try {
    const state = generateState();
    const authUrl = generateAuthUrl(state);
    
    console.log('[AUTH] Generated auth URL:', authUrl);
    
    const returnTo = url.searchParams.get('returnTo') || '/';
    
    logAuthEvent('Login initiated', { returnTo, authUrl });
    
    const stateData = JSON.stringify({ state, returnTo });
    
    const publicBaseUrl = process.env.PUBLIC_BASE_URL || '';
    const isProduction = process.env.NODE_ENV === 'production';
    const isSecure = publicBaseUrl.startsWith('https://') || isProduction;
    
    const stateCookie = serialize('auth_state', stateData, {
      httpOnly: true,
      secure: isSecure,
      sameSite: 'lax',
      maxAge: 600, // 10 minutes
      path: '/'
    });
    
    console.log('[AUTH] Setting auth state cookie:', stateCookie.substring(0, 50) + '...');
    
    return new Response(null, {
      status: 302,
      headers: {
        'Location': authUrl,
        'Set-Cookie': stateCookie
      }
    });
  } catch (error) {
    logAuthEvent('Login failed', { error: error instanceof Error ? error.message : 'Unknown error' });
    return new Response('Authentication error', { status: 500 });
  }
};