/**
 * E2E Test: Signup with OTP Email Verification via MailHog
 *
 * This test verifies:
 * 1. User can create an account
 * 2. OTP email is sent to MailHog
 * 3. OTP can be retrieved from MailHog API
 * 4. User can verify account with OTP
 */

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

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

// Helper: Get latest email from MailHog
async function getLatestEmail() {
  const response = await fetch(`${MAILHOG_API}/messages?limit=1`);
  const data = await response.json();
  return data.items?.[0];
}

// Helper: Extract OTP from email content
function extractOTP(emailBody: string): string | null {
  // Look for 6-digit OTP in the email
  const match = emailBody.match(/\b\d{6}\b/);
  return match ? match[0] : null;
}

// Helper: Clear all emails from MailHog
async function clearMailHog() {
  await fetch(`${MAILHOG_API}/messages`, { method: 'DELETE' });
}

test.describe('Signup with OTP Email Verification', () => {
  test.beforeEach(async () => {
    // Clear MailHog before each test
    await clearMailHog();
  });

  test('should send OTP email to MailHog on account creation', async ({ page }) => {
    const testEmail = `test-${Date.now()}@example.com`;
    const testPassword = 'TestPassword123!';
    const testName = 'Test User';

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

    // Fill out signup form
    await page.fill('input[name="email"]', testEmail);
    await page.fill('input[name="password"]', testPassword);
    await page.fill('input[name="fullName"]', testName);

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

    // Wait for success response
    await page.waitForTimeout(2000);

    // Check if email was sent to MailHog
    const email = await getLatestEmail();

    // Verify email exists
    expect(email).toBeDefined();
    expect(email.Content.Headers.To).toContain(testEmail);
    expect(email.Content.Headers.Subject).toContain('Verification Code');

    // Extract OTP from email
    const emailBody = email.Content.Body;
    const otp = extractOTP(emailBody);

    console.log(`✅ OTP extracted from email: ${otp}`);
    expect(otp).toBeTruthy();
    expect(otp).toMatch(/^\d{6}$/);

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

    // Fill in OTP
    if (otp) {
      await page.fill('input[name="otp"]', otp);
      await page.click('button[type="submit"]');

      // Should redirect to success page
      await expect(page).toHaveURL(/\/signup\/success/);
    }
  });

  test('should send OTP in Arabic when user selects Arabic', async ({ page }) => {
    const testEmail = `test-ar-${Date.now()}@example.com`;
    const testPassword = 'TestPassword123!';
    const testName = 'مستخدم تجريبي';

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

    // Fill out signup form
    await page.fill('input[name="email"]', testEmail);
    await page.fill('input[name="password"]', testPassword);
    await page.fill('input[name="fullName"]', testName);

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

    // Wait for success response
    await page.waitForTimeout(2000);

    // Check if email was sent to MailHog
    const email = await getLatestEmail();

    // Verify email exists and contains Arabic content
    expect(email).toBeDefined();
    expect(email.Content.Headers.To).toContain(testEmail);

    // Arabic subject should contain Arabic text
    const subject = email.Content.Headers.Subject?.[0];
    expect(subject).toContain('رمز التحقق') || expect(subject).toContain('Mawidi');

    // Extract OTP from email
    const emailBody = email.Content.Body;
    const otp = extractOTP(emailBody);

    console.log(`✅ Arabic OTP extracted: ${otp}`);
    expect(otp).toBeTruthy();
    expect(otp).toMatch(/^\d{6}$/);
  });

  test('should handle MailHog availability check', async () => {
    // Verify MailHog is accessible
    const response = await fetch(`${MAILHOG_API}/messages`);
    expect(response.ok).toBeTruthy();
    console.log('✅ MailHog API is accessible at http://localhost:8025');
  });
});
