import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Worktree containers with NBSP metadata are rejected", WEB, async ({ t3, app, screen, browser }) => {
  const source = await t3.project("source");
  const thread = await t3.thread({ project: source, title: "Container validation", messages: ["Hello"] });
  const root = await mkdtemp("/tmp/factory-pr-44477-evidence-1/containers-");
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  await git(source, "branch", "develop");
  for (const [name, meta] of [["container-plain", ".bare"], ["container-nbsp", ".bare\u00a0"]]) {
    const container = `${root}/${name}`;
    await mkdir(container);
    await git(container, "clone", "--bare", source, meta!);
    await writeFile(`${container}/.git`, `gitdir: ./${meta}\n`);
    await git(container, "worktree", "add", "develop", "develop");
    await git(container, "config", "core.bare", "false");
  }
  await browser.setViewport({ width: 1280, height: 900 });
  await t3.open(thread);
  const add = async (path: string) => {
    await screen.getByRole("combobox", "Projects").tap();
    await screen.getByRole("option", "Add project").tap();
    await screen.getByText("Local folder").tap();
    await screen.getByRole("combobox").fill(path);
    await browser.keyboard.press("Enter");
  };
  await add(`${root}/container-nbsp`);
  // Wait for either the rejection or the incorrectly created draft before capturing.
  await browser.locator('[aria-label="New thread in container-nbsp"], [data-slot="toast-title"]').first().waitFor();
  await runPromise(Effect.sleep("800 millis"));
  await app.screenshot("nbsp-container-result");
  await expect(screen.getByText(/holds a repository.s worktrees but is not a checkout itself/)).toBeVisible();
});
