// src/pages/api/auth/process.ts (FIXED - Proper cookie handling)
import type { APIRoute } from 'astro';
import { 
  verifyAuthState,
  exchangeCodeForTokens, 
  getUserInfo, 
  createSessionWithCookie,
  logAuthEvent
} from '../../../utils/auth.js';
import { apiError, apiSpecial, apiWithHeaders, handleAPIRequest } from '../../../utils/api.js';

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  return await handleAPIRequest(async () => {
    let body;
    try {
      body = await request.json();
    } catch (parseError) {
      console.error('JSON parse error:', parseError);
      return apiSpecial.invalidJSON();
    }
    
    const { code, state } = body || {};
    
    if (!code || !state) {
      logAuthEvent('Missing code or state parameter in process request');
      return apiSpecial.missingRequired(['code', 'state']);
    }
    
    const stateVerification = verifyAuthState(request, state);
    if (!stateVerification.isValid || !stateVerification.stateData) {
      return apiError.badRequest(stateVerification.error || 'Invalid state parameter');
    }
    
    const tokens = await exchangeCodeForTokens(code);
    const userInfo = await getUserInfo(tokens.access_token);
    
    const sessionResult = await createSessionWithCookie(userInfo);
    
    logAuthEvent('Authentication successful', { 
      userId: sessionResult.userId,
      email: sessionResult.userEmail 
    });
    
    const responseHeaders = new Headers();
    responseHeaders.set('Content-Type', 'application/json');
    
    responseHeaders.append('Set-Cookie', sessionResult.sessionCookie);
    responseHeaders.append('Set-Cookie', sessionResult.clearStateCookie);
    
    return new Response(JSON.stringify({ 
      success: true, 
      redirectTo: stateVerification.stateData.returnTo 
    }), {
      status: 200,
      headers: responseHeaders
    });
    
  }, 'Authentication processing failed');
};