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

test.use({ storageState: "playwright/.auth/viewer.json" });

test("can create user key", async ({ page }) => {
  // Navigate to the API Keys tab of the profile page
  await page.goto("/profile/api-keys");

  // Generate a unique key name for this test run
  const keyName = `key-${randomUUID()}`;

  // Click the "New Key" button to open the create dialog
  await page.getByRole("button", { name: "New Key" }).click();

  // Fill in the key name and submit
  await page.getByRole("dialog").getByLabel("Name").fill(keyName);
  await page.getByRole("button", { name: "Create Key" }).click();

  // Close the dialog that appears after creating the key
  await page
    .getByRole("dialog")
    .getByRole("button", { name: "dismiss" })
    .click();

  // Verify the named key appears in the list - which means key creation succeeded
  await expect(page.getByText(keyName, { exact: true })).toBeVisible();
});

test("should not be able to create a new project", async ({ page }) => {
  await page.goto("/projects");
  await page.waitForURL("**/projects");

  // Wait for the page to be loaded
  await expect(
    page.getByRole("searchbox", { name: "Search projects by name" })
  ).toBeVisible();

  await expect(
    page.getByRole("button", { name: "New Project" })
  ).not.toBeVisible();
});

test("projects table renders for viewers and allows filtering input", async ({
  page,
}) => {
  await page.goto("/projects");
  await page.waitForURL("**/projects");

  const search = page.getByRole("searchbox", {
    name: "Search projects by name",
  });
  await expect(search).toBeVisible();
  await search.fill(`viewer-search-${randomUUID().slice(0, 8)}`);
  await expect(search).toHaveValue(/viewer-search-/);
  await expect(
    page.getByRole("button", { name: "New Project" })
  ).not.toBeVisible();
});
