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

    // Parse request body
    const body = await readBody(event);
    console.log('[api/admin/test-email.post] Request body:', body);

    // Validate required fields
    if (!body.testEmail) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Test email address is required'
      });
    }

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

    console.log('[api/admin/test-email.post] Sending test email to:', body.testEmail);

    // Get email service and send test email
    const { getEmailService } = await import('~/server/utils/email');
    const emailService = await getEmailService();
    
    // Skip verification entirely and just try to send
    // Many SMTP servers don't support the VERIFY command
    console.log('[api/admin/test-email.post] Attempting to send test email without verification...');
    
    // Attempt to send test email directly
    await emailService.sendTestEmail(body.testEmail);

    console.log('[api/admin/test-email.post] ✅ Test email sent successfully');

    return {
      success: true,
      message: `Test email sent successfully to ${body.testEmail}`
    };

  } catch (error: any) {
    console.error('[api/admin/test-email.post] ❌ Error sending test email:', error);
    
    // Provide more specific error messages for common SMTP issues
    let errorMessage = error.message || 'Failed to send test email';
    
    if (error.code === 'EAUTH') {
      errorMessage = 'SMTP authentication failed. Please check your username and password.';
    } else if (error.code === 'ECONNECTION' || error.code === 'ETIMEDOUT') {
      errorMessage = 'Could not connect to SMTP server. Please check your host and port settings.';
    } else if (error.code === 'ESOCKET') {
      errorMessage = 'Socket error. Please check your network connection and SMTP settings.';
    }
    
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: errorMessage
    });
  }
});
