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

const recordedHead = "ba0aa647543c5a0901536b272cad3d817065c88d";
const branch = "t3-16463-settle-final";

test("A merged request confirms an existing local branch at its recorded head", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("checkout-proof");
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  await git("remote", "add", "origin", "https://gitlab.com/julius54/testinggitlab.git");
  await git("fetch", "origin", "main", branch);
  await git("reset", "--hard", "origin/main");
  await git("branch", branch, recordedHead);
  await git("branch", "--set-upstream-to", `origin/${branch}`, branch);
  const thread = await t3.thread({project, title: "Merged request checkout", messages: ["Ready"]});
  await t3.open(thread);
  await screen.getByRole("button", "New thread in checkout-proof", {exact:true}).tap();
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill("#2");
  const checkout = /Checkout (?:merge|pull|change) request/i;
  await screen.getByRole("option", checkout).tap();
  const dialog = screen.getByRole("dialog", checkout);
  await dialog.getByText("t3 #16463 settle check (final head)", {exact:true}).waitFor();
  await app.screenshot("merged-request-dialog");
  await dialog.getByRole("button", "Worktree", {exact:true}).tap();
  await dialog.waitFor({state:"hidden"});
  const warningCount = await browser.evaluate(() => [...document.querySelectorAll('[data-slot="toast-title"]')].filter(el => el.textContent?.includes("Checked out, but not confirmed on the latest commit")).length);
  await app.screenshot("recorded-head-checkout");
  const worktrees = (await git("worktree", "list", "--porcelain")).stdout;
  const block = worktrees.split("\n\n").find(item => item.includes(`branch refs/heads/${branch}`));
  expect(block?.includes(`HEAD ${recordedHead}`)).toBe(true);
  expect((await git("rev-parse", branch)).stdout.trim()).toBe(recordedHead);
  expect((await git("rev-parse", `origin/${branch}`)).stdout.trim()).not.toBe(recordedHead);
  expect(warningCount).toBe(0);
});
