/**
 * E2E Test: OTP Login → Billing Access Flow
 *
 * CRITICAL REGRESSION PREVENTION:
 * Ensures users who log in via OTP can access billing information
 *
 * This test reproduces the exact bug that occurred:
 * 1. User logs in via OTP (creates auth_token cookie)
 * 2. User navigates to dashboard billing tab
 * 3. Billing API must accept auth_token cookie (not just NextAuth session)
 * 4. User sees subscription details (not "Unauthorized" error)
 *
 * @see BILLING_AUTH_FIX.md
 */

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

test.describe('OTP Login → Billing Access Flow', () => {
  test.beforeEach(async ({ page }) => {
    // Start fresh - clear all cookies
    await page.context().clearCookies();
  });

  test('should access billing information after OTP login', async ({ page }) => {
    // Step 1: Navigate to login page
    await page.goto('http://localhost:9000/en/login');

    // Step 2: Enter email and request OTP
    await page.fill('input[type="text"]', 'guqo@mailinator.com');
    await page.click('button:has-text("Send OTP")');

    // Step 3: Wait for OTP input screen
    await expect(page.locator('text=Enter the code sent to you')).toBeVisible({
      timeout: 10000,
    });

    // Step 4: Get OTP from MailHog
    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto('http://localhost:8025/');

    // Wait for email list to load
    await mailhogPage.waitForSelector('text=Your Secure Login Code', { timeout: 5000 });

    // Click on the latest email to guqo@mailinator.com
    await mailhogPage.click('text=Your Secure Login Code >> nth=0');

    // Extract OTP from email content
    await mailhogPage.waitForSelector('iframe');
    const frame = mailhogPage.frameLocator('iframe');
    const otpText = await frame.locator('text=/\\d{6}/').textContent();
    const otp = otpText?.match(/\d{6}/)?.[0];

    expect(otp).toBeTruthy();
    expect(otp).toHaveLength(6);

    await mailhogPage.close();

    // Step 5: Enter OTP and log in
    await page.fill('input[placeholder*="OTP"]', otp!);
    await page.click('button:has-text("Verify and Log in")');

    // Step 6: Wait for dashboard to load
    await expect(page).toHaveURL(/.*\/dashboard/, { timeout: 15000 });
    await expect(page.locator('text=Welcome back')).toBeVisible();

    // Step 7: Verify auth_token cookie was created (not NextAuth session)
    const cookies = await page.context().cookies();
    const authTokenCookie = cookies.find((c) => c.name === 'auth_token');
    expect(authTokenCookie).toBeTruthy();
    console.log('✅ auth_token cookie created:', authTokenCookie?.value.substring(0, 20) + '...');

    // Step 8: Navigate to billing tab
    await page.click('button:has-text("Billing")');

    // Alternative: Direct URL navigation
    await page.goto('http://localhost:9000/en/dashboard?tab=billing');

    // Step 9: Wait for billing data to load
    await page.waitForLoadState('networkidle');

    // Step 10: CRITICAL - Verify NO "Unauthorized" error
    const unauthorizedError = page.locator('text=Unauthorized');
    await expect(unauthorizedError).not.toBeVisible();

    // Step 11: Verify subscription details are displayed
    // The page should show EITHER:
    // A) Active subscription details, OR
    // B) "Choose Your Perfect Plan" (if no subscription)
    // But should NOT show "Unauthorized" error

    const hasSubscription = await page.locator('text=You are currently on').isVisible();
    const needsSubscription = await page.locator('text=Choose Your Perfect Plan').isVisible();

    expect(hasSubscription || needsSubscription).toBe(true);

    // Step 12: If subscription exists, verify key details
    if (hasSubscription) {
      // Should show plan name
      await expect(page.locator('text=/Professional|Starter|Business|Enterprise|Ultimate/')).toBeVisible();

      // Should show status
      await expect(page.locator('text=/Active|trialing|Status/')).toBeVisible();

      // Should show pricing or upgrade options
      await expect(page.locator('text=/QAR|Monthly|Yearly|Upgrade/')).toBeVisible();

      console.log('✅ Subscription details displayed correctly');
    }

    // Step 13: Verify API calls succeeded (check network)
    // The /api/user/package-status call should have returned 200, not 401
    const apiCalls = await page.evaluate(() => {
      return (window as any).__API_CALLS__ || [];
    });

    console.log('✅ Test completed: OTP login → billing access successful');
  });

  test('should show subscription for user with active subscription', async ({ page }) => {
    // This test specifically uses the test account that HAS a subscription

    await page.goto('http://localhost:9000/en/login');

    // Login via OTP
    await page.fill('input[type="text"]', 'guqo@mailinator.com');
    await page.click('button:has-text("Send OTP")');

    await expect(page.locator('text=Enter the code sent to you')).toBeVisible({
      timeout: 10000,
    });

    // Get OTP from MailHog
    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto('http://localhost:8025/');
    await mailhogPage.waitForSelector('text=Your Secure Login Code', { timeout: 5000 });
    await mailhogPage.click('text=Your Secure Login Code >> nth=0');
    await mailhogPage.waitForSelector('iframe');
    const frame = mailhogPage.frameLocator('iframe');
    const otpText = await frame.locator('text=/\\d{6}/').textContent();
    const otp = otpText?.match(/\d{6}/)?.[0];
    await mailhogPage.close();

    // Enter OTP
    await page.fill('input[placeholder*="OTP"]', otp!);
    await page.click('button:has-text("Verify and Log in")');

    // Wait for dashboard
    await expect(page).toHaveURL(/.*\/dashboard/, { timeout: 15000 });

    // Navigate to billing
    await page.goto('http://localhost:9000/en/dashboard?tab=billing');
    await page.waitForLoadState('networkidle');

    // CRITICAL ASSERTIONS
    // 1. No unauthorized error
    await expect(page.locator('text=Unauthorized')).not.toBeVisible();

    // 2. Shows subscription (this user has tier2)
    await expect(page.locator('text=You are currently on')).toBeVisible({ timeout: 5000 });

    // 3. Shows plan name (Professional = tier2)
    await expect(page.locator('text=Professional')).toBeVisible();

    // 4. Shows status
    await expect(page.locator('text=trialing')).toBeVisible();

    // 5. Shows setup fee paid
    await expect(page.locator('text=Setup fee already paid')).toBeVisible();

    // 6. Shows upgrade options
    await expect(page.locator('text=Available Upgrades')).toBeVisible();

    console.log('✅ All subscription details visible with OTP auth');
  });

  test('should persist auth_token across page navigation', async ({ page }) => {
    // Login via OTP
    await page.goto('http://localhost:9000/en/login');
    await page.fill('input[type="text"]', 'guqo@mailinator.com');
    await page.click('button:has-text("Send OTP")');

    await expect(page.locator('text=Enter the code sent to you')).toBeVisible({
      timeout: 10000,
    });

    // Get OTP
    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto('http://localhost:8025/');
    await mailhogPage.waitForSelector('text=Your Secure Login Code', { timeout: 5000 });
    await mailhogPage.click('text=Your Secure Login Code >> nth=0');
    await mailhogPage.waitForSelector('iframe');
    const frame = mailhogPage.frameLocator('iframe');
    const otpText = await frame.locator('text=/\\d{6}/').textContent();
    const otp = otpText?.match(/\d{6}/)?.[0];
    await mailhogPage.close();

    await page.fill('input[placeholder*="OTP"]', otp!);
    await page.click('button:has-text("Verify and Log in")');

    await expect(page).toHaveURL(/.*\/dashboard/, { timeout: 15000 });

    // Get initial auth_token
    const cookies1 = await page.context().cookies();
    const authToken1 = cookies1.find((c) => c.name === 'auth_token')?.value;
    expect(authToken1).toBeTruthy();

    // Navigate to different tabs
    await page.click('button:has-text("WhatsApp")');
    await page.waitForTimeout(1000);

    await page.click('button:has-text("Billing")');
    await page.waitForTimeout(1000);

    await page.click('button:has-text("Analytics")');
    await page.waitForTimeout(1000);

    // Verify auth_token persists
    const cookies2 = await page.context().cookies();
    const authToken2 = cookies2.find((c) => c.name === 'auth_token')?.value;
    expect(authToken2).toBe(authToken1);

    // Navigate back to billing - should still work
    await page.goto('http://localhost:9000/en/dashboard?tab=billing');
    await page.waitForLoadState('networkidle');

    // Should NOT show unauthorized
    await expect(page.locator('text=Unauthorized')).not.toBeVisible();

    console.log('✅ auth_token persisted across navigation');
  });
});

/**
 * Comparison Test: NextAuth vs auth_token
 */
describe('Authentication Method Parity', () => {
  test('NextAuth and auth_token should provide same billing access', async ({ page }) => {
    // This test verifies that both auth methods provide equivalent access
    // We can't easily test NextAuth in Playwright, but we can verify
    // that auth_token provides the same result as documented for NextAuth

    await page.goto('http://localhost:9000/en/login');
    await page.fill('input[type="text"]', 'guqo@mailinator.com');
    await page.click('button:has-text("Send OTP")');

    await expect(page.locator('text=Enter the code sent to you')).toBeVisible({
      timeout: 10000,
    });

    const mailhogPage = await page.context().newPage();
    await mailhogPage.goto('http://localhost:8025/');
    await mailhogPage.waitForSelector('text=Your Secure Login Code', { timeout: 5000 });
    await mailhogPage.click('text=Your Secure Login Code >> nth=0');
    await mailhogPage.waitForSelector('iframe');
    const frame = mailhogPage.frameLocator('iframe');
    const otpText = await frame.locator('text=/\\d{6}/').textContent();
    const otp = otpText?.match(/\d{6}/)?.[0];
    await mailhogPage.close();

    await page.fill('input[placeholder*="OTP"]', otp!);
    await page.click('button:has-text("Verify and Log in")');

    await expect(page).toHaveURL(/.*\/dashboard/, { timeout: 15000 });

    // Access billing with OTP auth
    await page.goto('http://localhost:9000/en/dashboard?tab=billing');
    await page.waitForLoadState('networkidle');

    // Capture what's displayed
    const hasSubscriptionData = await page.locator('text=You are currently on').isVisible();
    const hasPlanSelector = await page.locator('text=Choose Your Perfect Plan').isVisible();
    const hasUnauthorized = await page.locator('text=Unauthorized').isVisible();

    // Document what auth_token provides
    console.log('OTP (auth_token) Access Results:');
    console.log('  - Has subscription data:', hasSubscriptionData);
    console.log('  - Shows plan selector:', hasPlanSelector);
    console.log('  - Shows unauthorized:', hasUnauthorized);

    // CRITICAL: Should NOT show unauthorized
    expect(hasUnauthorized).toBe(false);

    // Should show EITHER subscription data OR plan selector
    expect(hasSubscriptionData || hasPlanSelector).toBe(true);
  });
});
