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

    // Force reload and get SMTP configuration
    const { getSMTPConfig, 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/smtp-config.get] Failed to reload config, using cached version:', error);
    }
    
    const config = getSMTPConfig();
    console.log('[api/admin/smtp-config.get] Current SMTP config status:', {
      host: config.host || 'not set',
      port: config.port || 'not set',
      hasUsername: !!config.username,
      hasPassword: !!config.password,
      fromAddress: config.fromAddress || 'not set'
    });
    
    // Hide password for security
    const safeConfig = {
      ...config,
      password: config.password ? '••••••••••••••••' : ''
    };
    
    return {
      success: true,
      data: safeConfig
    };

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