import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const processId = "d6832ad3-bc10-4d37-bfba-18316825d2b1";
const org = process.env.AZURE_DEVOPS_TEST_ORG!.replace(/\/$/, "");
const project = encodeURIComponent(process.env.AZURE_DEVOPS_TEST_PROJECT!);
async function azure(path: string, method = "GET", body?: unknown, patch = false) {
  const response = await fetch(`${org}${path}${path.includes("?") ? "&" : "?"}api-version=7.1`, {
    method,
    headers: {
      Authorization: `Basic ${Buffer.from(`:${process.env.AZURE_DEVOPS_EXT_PAT}`).toString("base64")}`,
      "Content-Type": patch ? "application/json-patch+json" : "application/json",
    },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  if (!response.ok) throw new Error(`Azure setup ${method} failed: ${response.status} ${await response.text()}`);
  return response.status === 204 ? null : response.json();
}
const field = (name: string, value: string) => ({ op: "add", path: `/fields/System.${name}`, value });

test("Refresh includes a newly added Azure Completed state in Closed", WEB, async ({ t3, app, screen, browser }) => {
  const ids: number[] = [];
  let customState: string | undefined;
  try {
    const repos = await azure(`/${project}/_apis/git/repositories`);
    const baseline = await azure(`/${project}/_apis/wit/workitems/$Issue`, "POST", [field("Title", "Refresh proof: already Done")], true);
    ids.push(baseline.id);
    await azure(`/${project}/_apis/wit/workitems/${baseline.id}`, "PATCH", [field("State", "Done")], true);
    const target = await azure(`/${project}/_apis/wit/workitems/$Issue`, "POST", [field("Title", "Refresh proof: newly completed")], true);
    ids.push(target.id);
    const workspace = await t3.project("Azure refresh proof");
    execFileSync("git", ["remote", "add", "origin", repos.value[0].remoteUrl], { cwd: workspace });
    const thread = await t3.thread({ project: workspace, title: "Azure refresh verification", messages: ["Prepare issue refresh verification"] });
    await t3.open(thread);
    await screen.getByRole("button", "Issues", { exact: true }).tap();
    await screen.getByRole("button", "Filters", { exact: false }).tap();
    await screen.getByRole("menuitem", "State", { exact: false }).tap();
    await screen.getByRole("menuitemradio", "Closed", { exact: false }).tap();
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
    await screen.getByText("Refresh proof: already Done", { exact: true }).waitFor({ timeout: 120000 });
    await app.screenshot("initial-closed-list");
    const state = await azure(`/_apis/work/processes/${processId}/workItemTypes/Factory38986evidence.Issue/states`, "POST", { name: "Proof Completed", color: "339933", stateCategory: "Completed" });
    customState = state.id;
    await azure(`/${project}/_apis/wit/workitems/${target.id}`, "PATCH", [field("State", "Proof Completed")], true);
    await screen.getByRole("button", "Refresh issues", { exact: true }).tap();
    await browser.locator('button[aria-label="Refresh issues"]:not([disabled])').waitFor();
    await app.screenshot("closed-after-refresh");
    await expect(screen.getByText("Refresh proof: newly completed", { exact: true })).toBeVisible({ timeout: 30000 });
    await app.screenshot("closed-after-refresh");
  } finally {
    for (const id of ids) await azure(`/${project}/_apis/wit/workitems/${id}`, "DELETE");
    if (customState) await azure(`/_apis/work/processes/${processId}/workItemTypes/Factory38986evidence.Issue/states/${customState}`, "DELETE");
  }
});
