import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Webhook dedupe keys accept query and JSON paths containing spaces", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("webhook-demo");
  await t3.thread({ project, title: "Webhook setup", messages: ["Start"] });
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task").tap();
  await screen.getByRole("textbox", "Name").fill("PR webhook");
  await screen.getByRole("textbox", "Prompt").fill("Reply with OK. PR value: {{query.pull request}}");
  await screen.getByRole("button", "On webhook").tap();
  await screen.getByRole("textbox", "Duplicate request key template, optional", { exact: true }).fill("{{query.pull request}}");
  await screen.getByRole("textbox", "Coalesce key template, optional", { exact: true }).fill("{{body.pull request.id}}");
  await app.screenshot("spaced-webhook-keys");
  await screen.getByRole("button", "Create task").tap();
  try {
    await expect(screen.getByRole("button", "Actions for PR webhook")).toBeVisible({ timeout: 1000 });
  } finally {
    await app.screenshot("webhook-save-result");
  }
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = 'input[aria-label="Webhook URL"] { color: transparent !important; }';
    document.head.append(style);
    return null;
  });
  await screen.getByRole("button", "Actions for PR webhook").tap();
  await screen.getByRole("menuitem", "Edit", { exact: true }).tap();
  await screen.getByRole("textbox", "Webhook URL", { exact: true }).waitFor();
  await browser.evaluate(async () => {
    const input = document.querySelector<HTMLInputElement>('input[aria-label="Webhook URL"]')!;
    const url = new URL(input.value);
    url.searchParams.set("pull request", "42");
    for (const delivery of [1, 2]) {
      const response = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ "pull request": { id: 42 }, delivery }),
      });
      if (!response.ok) throw new Error(`Webhook returned ${response.status}`);
    }
    return null;
  });
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await screen.getByRole("button", "Actions for PR webhook").tap();
  await screen.getByRole("menuitem", "Deliveries").tap();
  try {
    await expect(screen.getByRole("dialog").getByText("Duplicate", { exact: true })).toBeVisible({ timeout: 1000 });
  } finally {
    await app.screenshot("repeated-webhook-delivery");
  }
});
