import { expect, test, type Page } from "@playwright/test";

const apiUrl = "http://localhost:5302/api";

async function login(page: Page) {
  await page.goto("/login");
  await page.getByLabel("Email").fill("e2e@example.test");
  await page.getByLabel("Current password").fill("E2ePassword123!");
  await page.getByRole("button", { name: "Sign in", exact: true }).click();
  await expect(page).toHaveURL(/\/dashboard$/);
  await expect(page.getByRole("heading", { name: "Dashboard", exact: true })).toBeVisible();
}

async function csrfHeader(page: Page) {
  const cookie = (await page.context().cookies()).find((value) => value.name === "XSRF-TOKEN");
  expect(cookie, "login should issue a CSRF cookie").toBeTruthy();
  return { "X-CSRF-TOKEN": cookie!.value };
}

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => window.localStorage.setItem("uiLanguage", "en"));
});

test("login establishes an authenticated session", async ({ page }) => {
  await login(page);
  await expect(page.getByText("e2e@example.test").first()).toBeVisible();
});

test("a saved job can be created through the reviewed UI flow", async ({ page }) => {
  const suffix = Date.now().toString();
  const title = `E2E Engineer ${suffix}`;

  await login(page);
  await page.goto("/jobs");
  await page.getByRole("button", { name: "Add Job" }).click();
  await page.getByRole("button", { name: "Enter details manually" }).click();
  await page.getByLabel("Company").fill(`E2E Company ${suffix}`);
  await page.getByLabel("Job title").fill(title);
  await page.getByRole("button", { name: "Continue" }).click();
  for (let step = 0; step < 3; step += 1) {
    await page.getByRole("button", { name: "Skip and continue" }).click();
  }
  await page.getByRole("button", { name: "Create job", exact: true }).click();

  await expect(page.getByText(title, { exact: true })).toBeVisible();
});

test("Career Workspace loads from the authenticated application shell", async ({ page }) => {
  await login(page);
  await page.goto("/career");
  await expect(page.getByRole("heading", { name: "Career Workspace" })).toBeVisible();
  await expect(page.getByText(/job-specific CVs stay separate/i)).toBeVisible();
});

test("a public CV renders anonymously and downloads as PDF", async ({ page }) => {
  await login(page);
  const headers = await csrfHeader(page);
  const create = await page.request.post(`${apiUrl}/cv/variants`, {
    headers,
    data: { name: "E2E Public CV" },
  });
  expect(create.ok()).toBeTruthy();
  const variant = await create.json();

  const publish = await page.request.put(`${apiUrl}/cv/variants/${variant.id}/public`, {
    headers,
    data: { isPublic: true },
  });
  expect(publish.ok()).toBeTruthy();
  const published = await publish.json();

  await page.context().clearCookies();
  await page.goto(`/cv/${published.publicSlug}`);
  await expect(page.getByTitle("Public CV")).toBeVisible();
  await expect(page.getByRole("link", { name: "Download PDF" })).toHaveAttribute("href", /\/pdf$/);
  const pdf = await page.request.get(`${apiUrl}/public-cv/${published.publicSlug}/pdf`);
  expect(pdf.ok()).toBeTruthy();
  expect(pdf.headers()["content-type"]).toContain("application/pdf");
  expect((await pdf.body()).subarray(0, 5).toString()).toBe("%PDF-");
});
