export default defineEventHandler(async (event) => {
  console.log('[api/admin/recaptcha-config.get] =========================');
  console.log('[api/admin/recaptcha-config.get] GET /api/admin/recaptcha-config - Get reCAPTCHA configuration');
  
  try {
    // Validate session and require admin privileges
    const sessionManager = createSessionManager();
    const cookieHeader = getCookie(event, 'monacousa-session') ? getHeader(event, 'cookie') : undefined;
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session?.user) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      });
    }

    if (session.user.tier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Admin privileges required'
      });
    }

    console.log('[api/admin/recaptcha-config.get] Authorized admin:', session.user.email);

    // Force reload and get reCAPTCHA configuration
    const { getRecaptchaConfig, reloadAdminConfig } = await import('~/server/utils/admin-config');
    
    // Force reload configuration to ensure we have the latest settings
    try {
      await reloadAdminConfig();
    } catch (error) {
      console.warn('[api/admin/recaptcha-config.get] Failed to reload config, using cached version:', error);
    }
    
    const config = getRecaptchaConfig();
    
    return {
      success: true,
      data: {
        siteKey: config.siteKey,
        secretKey: config.secretKey ? '••••••••••••••••' : ''
      }
    };

  } catch (error: any) {
    console.error('[api/admin/recaptcha-config.get] ❌ Error getting reCAPTCHA config:', error);
    throw error;
  }
});
