import { test, expect } from '@playwright/test';
import {
  takeScreenshot,
  setupConsoleErrorTracking,
  assertCleanPage,
} from './utils/test-helpers';

test.describe('Journey 5: Password Reset Flow', () => {
  let consoleErrors: string[];

  test.beforeEach(async ({ page }) => {
    consoleErrors = setupConsoleErrorTracking(page);
  });

  test('should display forgot password form', async ({ page }) => {
    await page.goto('/auth/forgot-password');
    await takeScreenshot(page, '16-forgot-password-page');

    await expect(page.locator('input[name="email"]')).toBeVisible();
    await expect(page.locator('button[type="submit"]')).toBeVisible();

    assertCleanPage(consoleErrors);
  });

  test('should submit forgot password and show success message', async ({ page }) => {
    await page.goto('/auth/forgot-password');
    await page.fill('input[name="email"]', 'someuser@example.com');
    await page.click('button[type="submit"]');
    await page.waitForTimeout(3000);
    await takeScreenshot(page, '17-forgot-password-submitted');

    // Should show success message (anti-enumeration: always returns success)
    const pageContent = await page.textContent('body');
    expect(pageContent).toContain('If an account exists');

    assertCleanPage(consoleErrors);
  });

  test('should show error on reset-password page without token', async ({ page }) => {
    await page.goto('/auth/reset-password');
    await page.waitForTimeout(1000);
    await takeScreenshot(page, '18-reset-password-no-token');

    // Should show error about invalid/missing token
    const pageContent = await page.textContent('body');
    expect(pageContent).toContain('Invalid reset link');

    assertCleanPage(consoleErrors);
  });

  test('should have a link back to login from forgot-password', async ({ page }) => {
    await page.goto('/auth/forgot-password');

    const loginLink = page.locator('a[href="/auth/login"]');
    await expect(loginLink).toBeVisible();

    assertCleanPage(consoleErrors);
  });
});
