import { readFile, symlink } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Organization labels are available and survive editing a Forgejo issue", WEB, async ({ t3, app, screen, browser }) => {
  const host = "http://localhost:3917";
  const keys = JSON.parse(await readFile(join(process.env.XDG_DATA_HOME!, "forgejo-cli", "keys.json"), "utf8"));
  const token = keys.hosts["localhost:3917"].token;
  const api = async (path: string, data?: unknown) => {
    const response = await fetch(`${host}/api/v1/${path}`, {
      method: data === undefined ? "GET" : "PUT",
      headers: { Authorization: `token ${token}`, "Content-Type": "application/json" },
      ...(data === undefined ? {} : { body: JSON.stringify(data) }),
    });
    if (!response.ok) throw new Error(`Forgejo seed request failed: ${response.status}`);
    return response.json();
  };
  const org = (await api("orgs/acme/labels")).find((label: { name: string }) => label.name === "priority/high");
  await api("repos/acme/web/issues/1/labels", { labels: [] });
  await api("repos/acme/web/issues/2/labels", { labels: [org.id] });
  await symlink(process.env.FORGEJO_CLI_PATH!, join(T3_HOME, "bin", "fj"));
  const project = await t3.project("web");
  await runPromise(run("git", ["remote", "add", "origin", `${host}/acme/web.git`], { cwd: project }));
  const thread = await t3.thread({ project, title: "Forgejo labels", messages: ["Ready"] });
  await t3.open(thread);
  await t3.open("/issues");

  await screen.getByText("Org label control", { exact: true }).tap();
  await screen.getByRole("combobox", "Change labels", { exact: true }).tap();
  await screen.getByRole("option", "bug", { exact: true }).tap();
  await browser.keyboard.press("Escape");
  // Both the success and refusal are terminal UI outcomes of this same edit.
  await screen.getByText(/^(bug|Could not change labels)$/, { visible: true }).first().waitFor();
  await app.screenshot("edit-existing-organization-label");

  await screen.getByText("Existing issue", { exact: true }).tap();
  await screen.getByRole("combobox", "Change labels", { exact: true }).tap();
  await screen.getByRole("combobox", "Search labels", { exact: true }).fill("priority");
  await app.screenshot("organization-label-search");
  await expect(screen.getByRole("option", "priority/high", { exact: true })).toBeVisible();
  await screen.getByRole("option", "priority/high", { exact: true }).tap();
  await browser.keyboard.press("Escape");
  await expect(screen.getByText("priority/high", { exact: true, visible: true }).first()).toBeVisible();
  await screen.getByRole("button", "Refresh issue", { exact: true }).tap();
  await expect(screen.getByText("priority/high", { exact: true, visible: true }).first()).toBeVisible();
  await app.screenshot("organization-label-applied");
  await expect.poll(async () => (await api("repos/acme/web/issues/1")).labels.map((label: { name: string }) => label.name)).toEqual(["priority/high"]);
  await expect((await api("repos/acme/web/issues/2")).labels.map((label: { name: string }) => label.name).sort()).toEqual(["bug", "priority/high"]);
});
