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

    // Parse request body
    const body = await readBody(event);
    console.log('[api/admin/smtp-config.post] Request body:', { 
      ...body, 
      password: body.password ? '••••••••••••••••' : '' 
    });

    // Validate required fields
    if (!body.host || !body.port || !body.fromAddress || !body.fromName) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Missing required SMTP configuration fields'
      });
    }

    // Validate email format
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(body.fromAddress)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid from address email format'
      });
    }

    // Validate port is a number
    const port = parseInt(body.port, 10);
    if (isNaN(port) || port < 1 || port > 65535) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Port must be a valid number between 1 and 65535'
      });
    }

    // Get existing configuration to preserve password if not changed
    const { getSMTPConfig } = await import('~/server/utils/admin-config');
    const existingConfig = getSMTPConfig();
    
    // Check if password is the masked value
    const isMaskedPassword = body.password === '••••••••••••••••';
    
    // Prepare configuration object
    const smtpConfig = {
      host: body.host.trim(),
      port: port,
      secure: Boolean(body.secure),
      username: body.username?.trim() || '',
      // If password is masked bullets, preserve existing password
      // If password is empty, clear it
      // Otherwise, use the new password
      password: isMaskedPassword 
        ? (existingConfig.password || '') 
        : (body.password?.trim() || ''),
      fromAddress: body.fromAddress.trim(),
      fromName: body.fromName.trim()
    };

    console.log('[api/admin/smtp-config.post] Saving SMTP config:', {
      ...smtpConfig,
      password: smtpConfig.password ? '••••••••••••••••' : '',
      passwordAction: isMaskedPassword ? 'preserved' : (body.password ? 'updated' : 'cleared')
    });

    // Save SMTP configuration
    const { saveSMTPConfig } = await import('~/server/utils/admin-config');
    await saveSMTPConfig(smtpConfig, session.user.email);

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

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

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