/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as FileSystem from "effect/FileSystem";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Returning to Diff keeps the selected commit's repository", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const api = `${project}/api`;
    yield* fs.makeDirectory(api);
    const git = (args: string[]) => run("git", args, {cwd: api});
    yield* git(["init", "--quiet", "--initial-branch=main"]);
    yield* fs.writeFileString(`${api}/README.md`, "API repository\n");
    yield* git(["add", "."]);
    const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"];
    yield* git([...author, "commit", "-qm", "Initial API commit"]);
    yield* git(["checkout", "-qb", "api-notes"]);
    yield* fs.writeFileString(`${api}/api-notes.txt`, "API notes\n");
    yield* git(["add", "."]);
    yield* git([...author, "commit", "-qm", "Add API notes"]);
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const snapshot = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if (snapshot._tag !== "Some" || snapshot.value.kind !== "snapshot") throw new Error("No snapshot");
    const item = snapshot.value.snapshot.projects.find(p => p.workspaceRoot === project)!;
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    yield* Effect.promise(async () => {
      const response = await fetch(`${app.baseUrl}/api/projects/mutate`, {method:"POST", headers:{authorization:`Bearer ${issued.stdout.trim()}`, "content-type":"application/json"}, body:JSON.stringify({type:"project.update",commandId:crypto.randomUUID(),projectId:item.id,trackedFolders:[{path:api,name:"api"}]})});
      if (!response.ok) throw new Error(await response.text());
    });
  }).pipe(Effect.scoped));
  const thread = await t3.thread({project, title:"Review API commit", messages:["Start"]});
  await browser.setViewport({width:1440,height:900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByRole("button", "Files F", {exact:true}).tap();
  await screen.getByRole("button", "Add panel surface").tap();
  await screen.getByRole("menuitem", /^Diff/).tap();
  await screen.getByRole("button", /^Repository:/).tap();
  await screen.getByRole("menuitemradio", "api", {exact:true}).tap();
  await screen.getByRole("combobox", /^Change comparison target/).tap();
  await screen.getByRole("option", "main", {exact:true}).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitem", "Commits", {exact:true}).hover();
  await screen.getByRole("menuitemradio", /^Add API notes/).tap();
  await screen.getByText("api-notes.txt", {exact:true}).first().waitFor();
  await app.screenshot("selected-api-commit");
  await browser.locator('[data-right-panel-tab-list] [data-active-tab]').filter({hasText:"Files"}).click();
  await browser.locator('[data-right-panel-tab-list] [data-active-tab]').filter({hasText:"Diff"}).click();
  await app.screenshot("returned-to-diff");
  await expect(screen.getByRole("button", "Repository: api", {exact:true})).toBeVisible();
  await expect(screen.getByText("api-notes.txt", {exact:true}).first()).toBeVisible();
});
