/**
 * Verify Single OTP Email Test
 *
 * This test verifies:
 * 1. Only ONE email is sent when user requests OTP
 * 2. The OTP in the email matches the one that can verify the account
 * 3. The OTP stored in Redis is the same as the one in the email
 */

import { test, expect } from '@playwright/test';

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

// Helper: Clear all emails from MailHog
async function clearMailHog() {
  await fetch('http://localhost:8025/api/v1/messages', { method: 'DELETE' });
}

// Helper: Get total email count
async function getEmailCount(): Promise<number> {
  const response = await fetch(`${MAILHOG_API}/messages`);
  const data = await response.json();
  return data.total || 0;
}

// Helper: Extract OTP from latest email
async function getOTPFromEmail(): Promise<string | null> {
  const response = await fetch(`${MAILHOG_API}/messages?limit=1`);
  const data = await response.json();
  const email = data.items?.[0];

  if (!email) return null;

  const body = email.Content.Body;
  const match = body.match(/\b(\d{6})\b/);
  return match ? match[1] : null;
}

test.describe('Single OTP Email Verification', () => {
  test('should send ONLY ONE email with correct OTP', async ({ page }) => {
    // Clear MailHog before test
    await clearMailHog();
    await page.waitForTimeout(1000);

    const initialCount = await getEmailCount();
    console.log(`📭 Initial email count: ${initialCount}`);
    expect(initialCount).toBe(0);

    // Navigate to signup page
    await page.goto('http://localhost:9000/en/signup');
    await page.waitForLoadState('networkidle');

    // Fill form with unique email
    const testEmail = `test-${Date.now()}@example.com`;
    await page.fill('input[name="email"]', testEmail);
    await page.fill('input[name="password"]', 'TestPassword123!');
    await page.fill('input[name="fullName"]', 'Test User');

    console.log(`📧 Creating account for: ${testEmail}`);

    // Submit signup form
    await page.click('button[type="submit"]');

    // Wait for OTP to be sent
    await page.waitForTimeout(3000);

    // Check email count - should be exactly 1
    const finalCount = await getEmailCount();
    console.log(`📬 Final email count: ${finalCount}`);

    expect(finalCount).toBe(1);
    console.log(`✅ Exactly ONE email sent (not duplicate)`);

    // Extract OTP from email
    const otpFromEmail = await getOTPFromEmail();
    console.log(`🔢 OTP extracted from email: ${otpFromEmail}`);

    expect(otpFromEmail).toBeTruthy();
    expect(otpFromEmail).toMatch(/^\d{6}$/);

    // Navigate to verify page (might auto-redirect)
    const currentUrl = page.url();
    if (!currentUrl.includes('/verify')) {
      await page.goto('http://localhost:9000/en/signup/verify');
    }

    // Enter the OTP from the email
    await page.fill('input[name="otp"]', otpFromEmail!);
    await page.click('button[type="submit"]');

    // Should succeed and redirect
    await page.waitForTimeout(2000);

    // Check if verification succeeded (could be success page or company-info)
    const finalUrl = page.url();
    const verificationSucceeded =
      finalUrl.includes('/success') ||
      finalUrl.includes('/company-info') ||
      finalUrl.includes('/dashboard');

    console.log(`🎯 Verification result: ${verificationSucceeded ? 'SUCCESS' : 'FAILED'}`);
    console.log(`   Final URL: ${finalUrl}`);

    expect(verificationSucceeded).toBeTruthy();
    console.log(`✅ OTP from email verified successfully`);
  });

  test('should send Arabic OTP email correctly', async ({ page }) => {
    // Clear MailHog
    await clearMailHog();
    await page.waitForTimeout(1000);

    // Navigate to Arabic signup
    await page.goto('http://localhost:9000/ar/signup');
    await page.waitForLoadState('networkidle');

    // Fill form
    const testEmail = `test-ar-${Date.now()}@example.com`;
    await page.fill('input[name="email"]', testEmail);
    await page.fill('input[name="password"]', 'TestPassword123!');
    await page.fill('input[name="fullName"]', 'مستخدم تجريبي');

    console.log(`📧 Creating Arabic account for: ${testEmail}`);

    // Submit
    await page.click('button[type="submit"]');
    await page.waitForTimeout(3000);

    // Verify exactly 1 email
    const count = await getEmailCount();
    console.log(`📬 Arabic email count: ${count}`);
    expect(count).toBe(1);

    // Extract OTP
    const otp = await getOTPFromEmail();
    console.log(`🔢 Arabic OTP: ${otp}`);
    expect(otp).toMatch(/^\d{6}$/);

    console.log(`✅ Single Arabic email sent with valid OTP`);
  });
});
