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

test.setTimeout(120_000);
const screenshotRoot = "../../../../specs/develop/20260623_2/m6_full_e2e";

async function openFirstRepositoryObject(page: import("@playwright/test").Page) {
  await page.goto("/");
  await page.getByRole("button", { name: /Repositories/i }).click();
  const reposSection = page.locator('section[aria-label="Repositories"]');
  await reposSection.getByLabel("Filter repositories on current page").fill("sakuya");
  await reposSection.locator(".stack-row-select").first().click();
  await page.locator('section[aria-label="Publication points"] .stack-row-select').first().click();
  const row = page.locator('section[aria-label="Objects for publication point"] tbody tr').first();
  await expect(row).toBeVisible({ timeout: 70_000 });
  const expectedUri = (await row.locator(".uri-cell .copyable-value-text").innerText()).trim();
  await row.getByRole("button", { name: "Open" }).click();
  await expect(page.locator(".object-detail-card")).toContainText(expectedUri, { timeout: 70_000 });
}

test("supports URI search and reports raw/export workflow status", async ({ page }) => {
  const apiRequests: string[] = [];
  page.on("request", (request) => {
    const url = new URL(request.url());
    if (url.pathname.startsWith("/api/v1")) {
      apiRequests.push(`${request.method()} ${url.pathname}${url.search}`);
    }
  });

  await openFirstRepositoryObject(page);

  await page.getByRole("button", { name: "Use selected URI" }).click();
  await page.getByPlaceholder("Exact URI lookup...").press("Enter");
  await expect.poll(
    () => apiRequests.some((request) => request.includes("/objects/by-uri")),
    { timeout: 30_000 }
  ).toBe(true);

  await page.getByRole("button", { name: "Download raw" }).click();
  await expect.poll(
    () => apiRequests.some((request) => request.includes("/raw")),
    { timeout: 30_000 }
  ).toBe(true);

  await page.getByRole("button", { name: "Export object" }).click();
  await expect(page.getByText(/Object export job|Object export failed/)).toBeVisible({ timeout: 30_000 });
  expect(apiRequests.some((request) => request.includes("POST /api/v1/runs/") && request.includes("/exports"))).toBe(true);

  await page.getByRole("button", { name: "Export selected PP" }).click();
  await expect(page.getByText(/PP export job|PP export failed/)).toBeVisible({ timeout: 30_000 });

  await page.screenshot({ path: `${screenshotRoot}/rpki-explorer-workflows.png`, fullPage: true });
});
