/**
 * Test OTP Email Sending with MailHog
 *
 * This tests the FULL OTP flow - generates OTP, stores in Redis, sends email
 * Usage: npx tsx scripts/test-email-otp.ts [language]
 */

// MUST load environment before any imports that use it
import { config } from 'dotenv';
config({ path: '.env.local' });

import { generateOTP, sendOTP } from '../lib/otp-storage';

async function testOTPEmail() {
  console.log('🧪 Testing Complete OTP Flow with MailHog...\n');

  const testEmail = 'test@example.com';
  const language = (process.argv[2] || 'en') as 'ar' | 'en';

  console.log(`📧 Testing ${language.toUpperCase()} OTP email`);
  console.log(`📬 Recipient: ${testEmail}`);

  // Generate OTP (same function used by API)
  const otp = generateOTP();
  console.log(`🔢 Generated OTP: ${otp}`);

  // Send OTP using the actual function that the API uses
  // This will:
  // 1. Hash and store OTP in Redis
  // 2. Send email via nodemailer to MailHog
  console.log(`\n📤 Sending OTP via sendOTP() function...`);
  const result = await sendOTP(testEmail, otp, language);

  if (result) {
    console.log(`✅ OTP sent successfully!`);
    console.log(`\n📊 What happened:`);
    console.log(`   1. OTP hashed and stored in Redis`);
    console.log(`   2. Email sent to MailHog (localhost:1025)`);
    console.log(`   3. Email captured and ready to view`);
    console.log(`\n🔍 Verification:`);
    console.log(`   - Open MailHog: http://localhost:8025`);
    console.log(`   - You should see 1 email with OTP: ${otp}`);
    console.log(`   - This is the SAME code stored in Redis`);
  } else {
    console.error(`❌ Failed to send OTP`);
    process.exit(1);
  }

  process.exit(0);
}

testOTPEmail().catch(error => {
  console.error('❌ Test failed:', error);
  process.exit(1);
});
