import { createSessionManager } from '~/server/utils/session';

export default defineEventHandler(async (event) => {
  console.log('[api/admin/recaptcha-config.post] =========================');
  console.log('[api/admin/recaptcha-config.post] POST /api/admin/recaptcha-config - Save 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.post] Authorized admin:', session.user.email);

    // Get and validate request body
    const body = await readBody(event);
    console.log('[api/admin/recaptcha-config.post] Request body fields:', Object.keys(body));

    // Validate required fields
    if (!body.siteKey || typeof body.siteKey !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Site Key is required'
      });
    }

    if (!body.secretKey || typeof body.secretKey !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: 'Secret Key is required'
      });
    }

    // Get existing configuration to preserve secretKey if not changed
    const { getRecaptchaConfig, saveRecaptchaConfig } = await import('~/server/utils/admin-config');
    const existingConfig = getRecaptchaConfig();
    
    // Check if secretKey is the masked value
    const isMaskedSecretKey = body.secretKey === '••••••••••••••••';
    
    // Save reCAPTCHA configuration
    await saveRecaptchaConfig({
      siteKey: body.siteKey.trim(),
      // If secretKey is masked bullets, preserve existing secretKey
      // Otherwise, use the new secretKey
      secretKey: isMaskedSecretKey 
        ? (existingConfig.secretKey || '') 
        : body.secretKey.trim()
    }, session.user.email);
    
    console.log('[api/admin/recaptcha-config.post] Secret key action:', 
      isMaskedSecretKey ? 'preserved' : 'updated');

    console.log('[api/admin/recaptcha-config.post] ✅ reCAPTCHA configuration saved successfully');

    return {
      success: true,
      message: 'reCAPTCHA configuration saved successfully'
    };

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