import type { APIRoute } from 'astro';
import { generateAuthUrl, generateState, logAuthEvent } from '../../../utils/auth.js';

export const prerender = false;

export const GET: APIRoute = async ({ url, redirect }) => {
  try {
    const state = generateState();
    const authUrl = generateAuthUrl(state);
    
    console.log('Generated auth URL:', authUrl);
    
    const returnTo = url.searchParams.get('returnTo') || '/';
    
    logAuthEvent('Login initiated', { returnTo, authUrl });
    
    const stateData = JSON.stringify({ state, returnTo });
    const stateCookie = `auth_state=${encodeURIComponent(stateData)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=600`;  
    
    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 });
  }
};