import { expect, test } from "@playwright/test";
import { installMockApi } from "./mockApi";

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

test("objects page lists all objects with server-side filters", async ({ page }) => {
  const requests: string[] = [];
  page.on("request", (req) => {
    if (req.url().includes("/objects?")) requests.push(req.url());
  });

  await page.goto("/objects");
  await expect(page.getByText("rsync://repo-a.example/ca1/alice.roa")).toBeVisible();
  await expect(page.getByText("rsync://repo-b.example/ca2/bob.asa")).toBeVisible();

  // Type filter is sent to the backend and narrows the rendered list
  await page.getByLabel("Type").selectOption("manifest");
  await expect.poll(() => requests.some((url) => url.includes("type=manifest"))).toBe(true);
  await expect(page.getByText("rsync://repo-a.example/ca1/manifest.mft")).toBeVisible();
  await expect(page.getByText("rsync://repo-b.example/ca2/bob.asa")).toBeHidden();

  // Rejected-only checkbox
  await page.getByLabel("Type").selectOption("");
  await page.getByRole("checkbox", { name: "Rejected only" }).click();
  await expect(page.getByRole("checkbox", { name: "Rejected only" })).toBeChecked();
  await expect.poll(() => requests.some((url) => url.includes("rejected=true"))).toBe(true);
  await expect(page.getByText("rsync://repo-a.example/ca1/stale.cer")).toBeVisible();
  await expect(page.getByText("rsync://repo-a.example/ca1/alice.roa")).toBeHidden();

  // URI substring filter
  await page.getByRole("checkbox", { name: "Rejected only" }).click();
  await expect(page.getByRole("checkbox", { name: "Rejected only" })).not.toBeChecked();
  await page.getByLabel("URI contains").fill("repo-b");
  await page.getByLabel("URI contains").press("Enter");
  await expect.poll(() => requests.some((url) => url.includes("q=repo-b"))).toBe(true);
  await expect(page.getByText("rsync://repo-b.example/ca2/bob.asa")).toBeVisible();
  await expect(page.getByText("rsync://repo-a.example/ca1/alice.roa")).toBeHidden();
});

test("objects page deep link applies filters from the URL", async ({ page }) => {
  await page.goto("/objects?type=certificate&rejected=true");
  await expect(page.getByLabel("Type")).toHaveValue("certificate");
  await expect(page.getByRole("checkbox", { name: "Rejected only" })).toBeChecked();
  await expect(page.getByText("rsync://repo-a.example/ca1/stale.cer")).toBeVisible();
  await expect(page.getByText("rsync://repo-a.example/ca1/alice.roa")).toBeHidden();
});

test("object row navigates to the object detail page", async ({ page }) => {
  await page.goto("/objects");
  await page.getByText("rsync://repo-a.example/ca1/alice.roa").click();
  await expect(page).toHaveURL(/\/objects\/obj-roa-0001/);
  await expect(page.getByText("ROA object")).toBeVisible();
});
