import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("Forgejo organization labels can be found, removed, and reapplied", WEB, async ({ t3, app, screen, browser }) => {
  const keys = JSON.parse(readFileSync(`${process.env.XDG_DATA_HOME}/forgejo-cli/keys.json`, "utf8"));
  const token = keys.hosts["127.0.0.1:3917"].token;
  const api = async (path: string, method = "GET", body?: unknown) => {
    const response = await fetch(`http://127.0.0.1:3917/api/v1${path}`, {
      method, headers: { Authorization: `token ${token}`, "Content-Type": "application/json" },
      ...(body === undefined ? {} : { body: JSON.stringify(body) }),
    });
    if (!response.ok) throw new Error(`Forgejo ${response.status}`);
    return response.status === 204 ? null : response.json();
  };
  await api("/repos/acme/web/issues/1/labels", "PUT", { labels: [1] });
  const workspace = await t3.project("web");
  execFileSync("git", ["remote", "add", "origin", "http://127.0.0.1:3917/acme/web.git"], { cwd: workspace });
  execFileSync("git", ["fetch", "origin"], { cwd: workspace });
  await t3.open();
  const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]));
  const { projects } = await (await fetch(`${app.baseUrl}/api/projects`, { headers: { Authorization: `Bearer ${issued.stdout.trim()}` } })).json();
  const project = projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === workspace);
  const environment = await runPromise(environmentId(app.baseUrl!));
  await t3.open(`/pull-requests?${new URLSearchParams({ repository: "acme/web", number: "1", selectedProjectId: project.id, selectedEnvironmentId: environment, selectedHost: "127.0.0.1:3917" })}`);
  await screen.getByRole("combobox", { name: "Change labels", exact: true }).click();
  await screen.getByText("bug", { exact: true }).waitFor();
  await app.screenshot("organization-label-picker");
  await screen.getByRole("combobox", { name: "Search labels", exact: true }).fill("security");
  await app.screenshot("search-organization-label");
  const security = screen.getByRole("option", { name: /security/ });
  await expect(security).toBeVisible();
  await expect(browser.locator('[aria-label="Applied"]')).toHaveCount(1);
  await security.click();
  await screen.getByRole("combobox", { name: "Search labels", exact: true }).press("Escape");
  await screen.getByRole("combobox", { name: "Change labels", exact: true }).click();
  await screen.getByRole("option", { name: /security/ }).waitFor();
  await expect(browser.locator('[aria-label="Applied"]')).toHaveCount(0);
  await app.screenshot("organization-label-removed");
  await screen.getByRole("option", { name: /security/ }).click();
  await screen.getByRole("combobox", { name: "Search labels", exact: true }).press("Escape");
  await screen.getByRole("combobox", { name: "Change labels", exact: true }).click();
  await expect(browser.locator('[aria-label="Applied"]')).toHaveCount(1);
  await app.screenshot("organization-label-reapplied");
  expect((await api("/repos/acme/web/issues/1/labels")).map((label: { name: string }) => label.name)).toEqual(["security"]);
});
