/**
 * Quick Passwordless Verification Script
 *
 * Verifies that passwordless authentication is working correctly
 * by testing the key endpoints and flows
 */

const APP_URL = 'http://localhost:9000';
const MAILHOG_API = 'http://localhost:8025/api/v2';

async function clearMailHog() {
  await fetch(`${MAILHOG_API}/messages`, { method: 'DELETE' });
}

async function getLatestEmail(email) {
  const response = await fetch(`${MAILHOG_API}/messages`);
  const data = await response.json();

  const userEmail = data.items.find(item => {
    const toHeader = item.Content?.Headers?.To?.[0] || '';
    return toHeader.includes(email);
  });

  return userEmail;
}

function extractOTP(emailData) {
  const body = emailData?.Content?.Body || '';
  const match = body.match(/(\d{6})/);
  return match ? match[1] : null;
}

async function testCheckEmail() {
  console.log('\n🧪 Test 1: Email Existence Check');
  console.log('=' .repeat(50));

  // Test with existing email
  const existingEmail = 'gara2222ge@support.com';
  const response = await fetch(`${APP_URL}/api/auth/check-email?email=${encodeURIComponent(existingEmail)}`);
  const data = await response.json();

  if (response.ok && data.exists) {
    console.log('✅ Existing email detected correctly');
    console.log(`   Email: ${existingEmail}`);
    console.log(`   Exists: ${data.exists}`);
    console.log(`   Verified: ${data.verified}`);
  } else {
    console.log('❌ Failed to check existing email');
    return false;
  }

  // Test with new email
  const newEmail = `test-${Date.now()}@example.com`;
  const response2 = await fetch(`${APP_URL}/api/auth/check-email?email=${encodeURIComponent(newEmail)}`);
  const data2 = await response2.json();

  if (response2.ok && !data2.exists) {
    console.log('✅ New email detected as available');
    console.log(`   Email: ${newEmail}`);
    console.log(`   Available: ${data2.available}`);
  } else {
    console.log('❌ Failed to check new email');
    return false;
  }

  return true;
}

async function testPasswordlessSignup() {
  console.log('\n🧪 Test 2: Passwordless Signup OTP');
  console.log('='.repeat(50));

  const testEmail = `passwordless-signup-${Date.now()}@example.com`;

  await clearMailHog();

  // Send OTP
  const response = await fetch(`${APP_URL}/api/send-otp`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: testEmail,
      language: 'en',
    }),
  });

  if (!response.ok) {
    console.log('❌ Failed to send OTP');
    const error = await response.json();
    console.log('   Error:', error);
    return false;
  }

  console.log('✅ OTP request sent');

  // Wait for email
  await new Promise(resolve => setTimeout(resolve, 2000));

  // Get email from MailHog
  const emailData = await getLatestEmail(testEmail);

  if (!emailData) {
    console.log('❌ No email received in MailHog');
    return false;
  }

  console.log('✅ Email received in MailHog');

  // Verify professional template
  const subject = emailData.Content.Headers.Subject[0];
  console.log(`   Subject: ${subject}`);

  const body = emailData.Content.Body;

  if (body.includes('gradient') && body.includes('Security Notice')) {
    console.log('✅ Professional email template used');
  } else {
    console.log('⚠️  Email template might not be the new professional version');
  }

  // Extract OTP
  const otp = extractOTP(emailData);

  if (otp) {
    console.log(`✅ OTP code found: ${otp}`);
  } else {
    console.log('❌ No OTP code in email');
    return false;
  }

  return true;
}

async function testPasswordlessLogin() {
  console.log('\n🧪 Test 3: Passwordless Login OTP');
  console.log('='.repeat(50));

  const testEmail = 'gara2222ge@support.com'; // Existing account

  await clearMailHog();

  // Request OTP for login
  const response = await fetch(`${APP_URL}/api/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      identifier: testEmail,
      useOTP: true,
      language: 'en',
    }),
  });

  if (!response.ok) {
    console.log('❌ Failed to request login OTP');
    const error = await response.json();
    console.log('   Error:', error);
    return false;
  }

  const data = await response.json();

  if (data.requiresOTP) {
    console.log('✅ Login OTP requested successfully');
  } else {
    console.log('❌ Response did not indicate OTP required');
    return false;
  }

  // Wait for email
  await new Promise(resolve => setTimeout(resolve, 2000));

  // Get email
  const emailData = await getLatestEmail(testEmail);

  if (!emailData) {
    console.log('❌ No login email received');
    return false;
  }

  console.log('✅ Login email received');

  // Check for personalization
  const body = emailData.Content.Body;

  if (body.match(/Hello \w+|مرحباً \w+/)) {
    console.log('✅ Email is personalized with name');
  } else {
    console.log('⚠️  Email might not be personalized');
  }

  // Check for login-specific message
  if (body.match(/log.*in.*account|requested to log in/i)) {
    console.log('✅ Email has login-specific message');
  } else {
    console.log('⚠️  Email might not have login-specific message');
  }

  const otp = extractOTP(emailData);

  if (otp) {
    console.log(`✅ Login OTP code found: ${otp}`);
  } else {
    console.log('❌ No OTP in login email');
    return false;
  }

  return true;
}

async function testBilingual() {
  console.log('\n🧪 Test 4: Bilingual Email Support');
  console.log('='.repeat(50));

  await clearMailHog();

  // Send Arabic OTP
  const arEmail = `arabic-${Date.now()}@example.com`;
  await fetch(`${APP_URL}/api/send-otp`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: arEmail,
      language: 'ar',
    }),
  });

  await new Promise(resolve => setTimeout(resolve, 2000));

  const arEmailData = await getLatestEmail(arEmail);

  if (arEmailData) {
    const subject = arEmailData.Content.Headers.Subject[0];
    if (subject.includes('رمز')) {
      console.log('✅ Arabic email sent with Arabic subject');
      console.log(`   Subject: ${subject}`);
    } else {
      console.log('⚠️  Arabic subject might be missing');
    }
  }

  // Send English OTP
  await clearMailHog();
  const enEmail = `english-${Date.now()}@example.com`;
  await fetch(`${APP_URL}/api/send-otp`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      email: enEmail,
      language: 'en',
    }),
  });

  await new Promise(resolve => setTimeout(resolve, 2000));

  const enEmailData = await getLatestEmail(enEmail);

  if (enEmailData) {
    const subject = enEmailData.Content.Headers.Subject[0];
    console.log('✅ English email sent');
    console.log(`   Subject: ${subject}`);
  }

  return true;
}

async function runAllTests() {
  console.log('\n🚀 Starting Passwordless Authentication Verification');
  console.log('=' .repeat(50));

  const results = [];

  try {
    results.push(await testCheckEmail());
  } catch (error) {
    console.error('❌ Test 1 failed:', error.message);
    results.push(false);
  }

  try {
    results.push(await testPasswordlessSignup());
  } catch (error) {
    console.error('❌ Test 2 failed:', error.message);
    results.push(false);
  }

  try {
    results.push(await testPasswordlessLogin());
  } catch (error) {
    console.error('❌ Test 3 failed:', error.message);
    results.push(false);
  }

  try {
    results.push(await testBilingual());
  } catch (error) {
    console.error('❌ Test 4 failed:', error.message);
    results.push(false);
  }

  console.log('\n' + '='.repeat(50));
  console.log('  Test Results Summary');
  console.log('='.repeat(50));
  console.log('');

  const passed = results.filter(r => r === true).length;
  const total = results.length;

  console.log(`Tests Passed: ${passed}/${total}`);
  console.log('');

  if (passed === total) {
    console.log('✅ All tests PASSED! Passwordless system is working correctly.');
    console.log('');
    console.log('Next steps:');
    console.log('1. Run full E2E tests: npm run test:e2e');
    console.log('2. Test manually at: http://localhost:9000/en/signup');
    console.log('3. Check MailHog at: http://localhost:8025');
    console.log('');
    process.exit(0);
  } else {
    console.log('❌ Some tests failed. Please review the output above.');
    console.log('');
    process.exit(1);
  }
}

runAllTests().catch((error) => {
  console.error('\n❌ Fatal error:', error);
  process.exit(1);
});
