import { copyFileSync, readFileSync } from "node:fs";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Labels reflect a host write that only partly succeeded", WEB, async ({t3, app, screen, browser}) => {
  copyFileSync(process.env.PROOF_FJ_BINARY!, `${T3_HOME}/bin/fj`);
  const token = readFileSync(process.env.PROOF_TOKEN_FILE!, "utf8").trim();
  const reset = await fetch("http://127.0.0.1:39135/api/v1/repos/demo/labels/issues/1/labels", {
    method: "PUT", headers: {Authorization: `token ${token}`, "Content-Type": "application/json"}, body: JSON.stringify({labels:[1,2]}),
  });
  if (!reset.ok) throw new Error("Could not restore both host labels");
  const project = await t3.project("Release documentation");
  await runPromise(run("git", ["remote", "add", "origin", "http://127.0.0.1:39136/demo/labels.git"], {cwd:project}));
  await t3.open("/pull-requests?host=127.0.0.1%3A39136");
  await screen.getByText("Document the release", {exact:true}).tap();
  await screen.getByRole("combobox", "Change labels", {exact:true}).tap();
  await screen.getByRole("option", /^documentation(?: Applied)?$/).tap();
  await screen.getByRole("option", /^needs review(?: Applied)?$/).tap();
  await browser.keyboard.press("Escape");
  await screen.getByText("Could not take documentation, needs review off", {exact:true}).waitFor();
  const host = await fetch("http://127.0.0.1:39135/api/v1/repos/demo/labels/issues/1/labels", {headers:{Authorization:`token ${token}`}}).then(r=>r.json());
  if (JSON.stringify(host.map((l: {name:string})=>l.name)) !== '["needs review"]') throw new Error("Host did not retain exactly needs review");
  await screen.getByText("Could not take documentation, needs review off", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("labels-row-after-failure");
  await screen.getByRole("combobox", "Change labels", {exact:true}).tap();
  try {
    await expect(screen.getByRole("option", /^documentation(?: Applied)?$/).getByRole("image", "Applied")).not.toBeVisible();
    await expect(screen.getByRole("option", /^needs review(?: Applied)?$/).getByRole("image", "Applied")).toBeVisible();
  } finally {
    await app.screenshot("labels-picker-after-failure");
  }
});
