/**
 * E2E — Password reset flow
 *
 * Requires:
 *  - Dev server running on http://localhost:3100
 *  - Mailhog running on http://localhost:8025
 *  - SMTP_HOST=localhost, SMTP_PORT=1025, SMTP_TLS=false configured
 *
 * Uses a dedicated test user "reset-test@planarchy.dev" created by global-setup.ts.
 * This avoids touching admin/manager/viewer passwords that other E2E suites depend on.
 *
 * Cleanup: afterEach resets the password back to Dev123456! via the reset-password
 * API + a direct DB token read (no email roundtrip needed for teardown).
 */
import { expect, test } from "@playwright/test";
import { clearMailhog, extractUrlFromEmail, getLatestEmailTo, resetPasswordViaApi, signIn } from "./helpers.js";

const BASE_URL = "http://localhost:3100";
const RESET_USER = { email: "reset-test@planarchy.dev", originalPassword: "Dev123456!" };
const NEW_PASSWORD = "ResetPass456!";

test.describe("password reset flow", () => {
  // No storageState — these tests exercise the unauthenticated flow

  test.beforeEach(async () => {
    await clearMailhog();
  });

  test.afterEach(async () => {
    // Always restore the original password so subsequent runs start clean.
    // Uses direct DB token read — no email roundtrip needed in teardown.
    try {
      await resetPasswordViaApi(BASE_URL, RESET_USER.email, RESET_USER.originalPassword);
    } catch (err) {
      console.warn("[afterEach] Password cleanup failed (may already be correct):", err);
    }
  });

  test("user can reset password via email link", async ({ page }) => {
    // Step 1: Request reset
    await page.goto("/auth/forgot-password");
    await page.fill('input[type="email"]', RESET_USER.email);
    await page.click('button[type="submit"]');

    // Step 2: Confirm success state (timing-safe — shown for any email)
    await expect(page.locator("text=Check your email")).toBeVisible({ timeout: 10_000 });

    // Step 3: Read reset email from Mailhog
    const email = await getLatestEmailTo(RESET_USER.email, { timeoutMs: 15_000 });
    expect(email.subject).toMatch(/reset/i);

    const resetPath = new URL(extractUrlFromEmail(email, "/auth/reset-password/")).pathname;

    // Step 4: Visit reset link
    await page.goto(resetPath);
    await expect(page.locator("text=Set a new password")).toBeVisible({ timeout: 10_000 });

    // Step 5: Set new password
    const passwordInputs = page.locator('input[type="password"]');
    await passwordInputs.nth(0).fill(NEW_PASSWORD);
    await passwordInputs.nth(1).fill(NEW_PASSWORD);
    await page.click('button[type="submit"]');

    await expect(page.locator("text=Password updated")).toBeVisible({ timeout: 15_000 });

    // Step 6: Sign in with new password
    await page.click('button:has-text("Go to sign in")');
    await page.waitForURL(/\/auth\/signin/);

    await signIn(page, RESET_USER.email, NEW_PASSWORD);
    await page.waitForURL(/\/(dashboard|resources)/, { timeout: 15_000 });
  });

  test("invalid reset token shows an error message", async ({ page }) => {
    await page.goto("/auth/reset-password/this-token-does-not-exist");

    await page.waitForSelector('input[type="password"]');
    const inputs = page.locator('input[type="password"]');
    await inputs.nth(0).fill("SomePass1!");
    await inputs.nth(1).fill("SomePass1!");
    await page.click('button[type="submit"]');

    // Error div with red styling should appear
    await expect(page.locator('[class*="red"]').first()).toBeVisible({ timeout: 10_000 });
  });
});
