#!/usr/bin/env node
/**
 * Email Configuration Test Script
 * Tests the email system to ensure password reset emails will work correctly
 */

const http = require('http');
const path = require('path');

const PORT = process.env.CHAT_PORT || 4000;
const HOST = process.env.CHAT_HOST || 'localhost';

console.log('🧪 Testing Email Configuration...\n');

// Test 1: Check if server is running
function testServerRunning() {
  return new Promise((resolve) => {
    const req = http.request({
      hostname: HOST,
      port: PORT,
      path: '/api/health',
      method: 'GET',
      timeout: 5000
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const json = JSON.parse(data);
          resolve({ success: json.ok, message: 'Server is running' });
        } catch (e) {
          resolve({ success: false, message: 'Invalid response from server' });
        }
      });
    });
    req.on('error', () => resolve({ success: false, message: 'Server not responding' }));
    req.on('timeout', () => {
      req.destroy();
      resolve({ success: false, message: 'Connection timed out' });
    });
    req.end();
  });
}

// Test 2: Preview password reset email template
function testEmailPreview() {
  return new Promise((resolve) => {
    const req = http.request({
      hostname: HOST,
      port: PORT,
      path: '/debug/email/preview?type=reset&email=test@example.com&token=test-token-123',
      method: 'GET',
      timeout: 10000
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        const hasBrandedHtml = data.includes('Plugin Compass') &&
                              data.includes('renderBrandedEmail') === false &&
                              data.includes('#004225');
        const hasResetLink = data.includes('reset-password');
        const hasButton = data.includes('Reset password');

        resolve({
          success: hasBrandedHtml && hasResetLink && hasButton,
          message: hasBrandedHtml && hasResetLink && hasButton
            ? 'Email template renders correctly with branding'
            : 'Email template missing required elements',
          details: {
            hasBranding: hasBrandedHtml,
            hasResetLink: hasResetLink,
            hasButton: hasButton
          }
        });
      });
    });
    req.on('error', () => resolve({ success: false, message: 'Failed to connect to preview endpoint' }));
    req.on('timeout', () => {
      req.destroy();
      resolve({ success: false, message: 'Preview request timed out' });
    });
    req.end();
  });
}

async function runTests() {
  console.log('Test 1: Server Status');
  console.log('─'.repeat(50));
  const serverTest = await testServerRunning();
  console.log(`  ${serverTest.success ? '✓' : '✗'} ${serverTest.message}`);
  console.log('');

  if (!serverTest.success) {
    console.log('❌ Server is not running. Start it with: node chat/server.js');
    process.exit(1);
  }

  console.log('Test 2: Email Template Preview');
  console.log('─'.repeat(50));
  const previewTest = await testEmailPreview();
  console.log(`  ${previewTest.success ? '✓' : '✗'} ${previewTest.message}`);
  if (previewTest.details) {
    console.log(`    - Has Plugin Compass branding: ${previewTest.details.hasBranding ? '✓' : '✗'}`);
    console.log(`    - Has reset password link: ${previewTest.details.hasResetLink ? '✓' : '✗'}`);
    console.log(`    - Has CTA button: ${previewTest.details.hasButton ? '✓' : '✗'}`);
  }
  console.log('');

  console.log('─'.repeat(50));
  console.log('📧 Email System Status:');
  console.log('');
  console.log('  The email system is ready. To send actual emails:');
  console.log('');
  console.log('  1. Edit the .env file and configure SMTP settings:');
  console.log('     SMTP_HOST=smtp.gmail.com');
  console.log('     SMTP_PORT=587');
  console.log('     SMTP_USER=your-email@gmail.com');
  console.log('     SMTP_PASS=your-app-password');
  console.log('     SMTP_FROM=noreply@yourdomain.com');
  console.log('');
  console.log('  2. For Gmail, create an app password at:');
  console.log('     https://myaccount.google.com/apppasswords');
  console.log('');
  console.log('  3. Restart the server:');
  console.log('     node chat/server.js');
  console.log('');
  console.log('  4. Test with: node scripts/test-email.js');
  console.log('');
  console.log('💡 Password reset emails include:');
  console.log('   - Professional Plugin Compass branding');
  console.log('   - Green gradient CTA button');
  console.log('   - Mobile-responsive design');
  console.log('   - One-click reset link');
  console.log('');
}

runTests().catch(console.error);
