import { randomBytes } from 'crypto';

export default defineEventHandler(async (event) => {
  console.log('🔐 Login endpoint called at:', new Date().toISOString());
  
  try {
    const config = useRuntimeConfig();
    console.log('🔧 Keycloak config:', {
      issuer: config.keycloak?.issuer || 'NOT SET',
      clientId: config.keycloak?.clientId || 'NOT SET',
      callbackUrl: config.keycloak?.callbackUrl || 'NOT SET',
      hasSecret: !!config.keycloak?.clientSecret
    });

    if (!config.keycloak?.issuer || !config.keycloak?.clientId || !config.keycloak?.clientSecret) {
      console.error('❌ Missing Keycloak configuration');
      throw createError({
        statusCode: 500,
        statusMessage: 'Keycloak configuration is incomplete'
      });
    }

    const keycloak = createKeycloakClient();
    const state = randomBytes(32).toString('hex');
    
    // Get cookie domain from environment
    const cookieDomain = process.env.COOKIE_DOMAIN || undefined;
    console.log('🍪 Cookie domain:', cookieDomain);
    
    // Store state in session for verification
    setCookie(event, 'oauth-state', state, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      domain: cookieDomain,
      maxAge: 600, // 10 minutes
    });

    const authUrl = keycloak.getAuthUrl(state);
    console.log('🔗 Redirecting to Keycloak:', authUrl);
    
    return sendRedirect(event, authUrl);
  } catch (error) {
    console.error('❌ Login error:', error);
    throw error;
  }
});
