import { defineEventHandler, createError } from 'h3';
import { getSessionFromCookie } from '~/server/utils/sessionStore';

export default defineEventHandler(async (event) => {
  console.log('🌐 Proxy: External token validation requested');
  
  const config = useRuntimeConfig();
  
  try {
    // 1. Get current session to retrieve access token
    const session = await getSessionFromCookie(event);
    
    if (!session || !session.accessToken) {
      console.log('❌ Proxy: No valid session or access token found');
      throw createError({
        statusCode: 401,
        statusMessage: 'Unauthorized: No valid session found',
      });
    }
    
    const accessToken = session.accessToken;
    
    // Log token details for debugging audience and claims
    try {
      const payloadPart = accessToken.split('.')[1];
      const payload = JSON.parse(Buffer.from(payloadPart, 'base64').toString());
      console.log('🎫 Full Token Payload:', JSON.stringify(payload, null, 2));
      console.log('🎫 Token Audience (aud):', payload.aud);
    } catch (e) {
      console.warn('⚠️ Proxy: Failed to parse token for logging');
    }

    const externalApiUrl = `${config.externalApiBaseUrl}/api/v1/auth/me`;
    
    console.log(`📡 Proxy: Calling external API: ${externalApiUrl}`);
    
    // 2. Call external API with Bearer token
    // We use $fetch from ofetch (auto-imported in Nuxt/Nitro)
    const response = await $fetch(externalApiUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Accept': 'application/json',
      },
      timeout: config.externalApiTimeout || 10000,
    });
    
    console.log('✅ Proxy: External API call successful');
    
    return {
      success: true,
      data: response,
      timestamp: new Date().toISOString()
    };
    
  } catch (error: any) {
    console.error('❌ Proxy: External API call failed:', error.message);
    
    // Check if it's an HTTP error from the external API
    const statusCode = error.response?.status || 500;
    const statusText = error.response?.statusText || 'External API Error';
    const errorData = error.response?._data || error.data || null;
    
    console.error(`   Status: ${statusCode} ${statusText}`);
    if (errorData) {
      console.error('   Error Data:', JSON.stringify(errorData));
    }
    
    return {
      success: false,
      error: statusText,
      statusCode: statusCode,
      details: errorData || error.message,
      timestamp: new Date().toISOString()
    };
  }
});
