import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("First commit restores the open draft repository picker", WEB, async ({ t3, app, browser, screen }) => {
  const folder = await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    yield* fs.makeDirectory(path.join(T3_HOME, "workspaces"), { recursive: true });
    const parent = yield* fs.makeTempDirectory({ directory: path.join(T3_HOME, "workspaces"), prefix: "w-" });
    const folder = path.join(parent, "services");
    const api = path.join(folder, "api");
    yield* fs.makeDirectory(api, { recursive: true });
    yield* run("git", ["init", "--quiet", "--initial-branch=main"], { cwd: api });
    return folder;
  }));
  const added = await runPromise(makeState(T3_HOME).cli(["project", "add", folder]));
  const projectId = /Added project (\S+) /.exec(added.stdout)?.[1];
  if (!projectId) throw new Error("Project was not added");
  t3.trackProject(projectId);
  await t3.open();
  const workspace = browser.locator('[data-composer-shortcut="composer.workspace"]');
  await screen.getByRole("textbox").fill("Plan the services implementation");
  await workspace.tap();
  await screen.getByRole("option", "New worktree", { exact: true }).tap();
  await app.screenshot("before-first-commit");
  await runPromise(run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Initial commit"], { cwd: `${folder}/api` }));
  await browser.evaluate(() => {
    window.dispatchEvent(new FocusEvent("focus"));
    document.dispatchEvent(new Event("visibilitychange"));
  });
  await workspace.tap();
  await screen.getByRole("option", "Current checkout", { exact: true }).tap();
  await workspace.tap();
  await screen.getByRole("option", "New worktree", { exact: true }).tap();
  await app.screenshot("repository-picker-after-first-commit");
  const repositories = screen.getByRole("button", /^Repositories in the new worktree/);
  await expect(repositories).toBeVisible();
  await repositories.tap();
  await app.screenshot("api-is-selectable");
  await expect(screen.getByRole("menuitemcheckbox", "api", { exact: true })).toBeVisible();
});
