/// <reference lib="dom" />
import { CommandId, EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Reopened repository rows show current staged change counts", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo", {".gitignore": "/library/\n"});
  const repository = `${project}/library`;
  const stage = (content: string) => runPromise(Effect.gen(function*() {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${repository}/source.txt`, content);
    yield* run("git", ["add", "source.txt"], {cwd: repository});
  }));
  await runPromise(Effect.gen(function*() {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(repository);
    yield* run("git", ["init", "--initial-branch=main"], {cwd: repository});
    yield* fs.writeFileString(`${repository}/source.txt`, "original\n");
    yield* run("git", ["add", "source.txt"], {cwd: repository});
    yield* run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Baseline"], {cwd: repository});
    const {stdout} = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = {authorization: `Bearer ${stdout.trim()}`};
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, {baseUrl: app.baseUrl});
    const {projects} = yield* client.projects.snapshot({headers});
    const entry = projects.find(p => p.workspaceRoot === project)!;
    yield* client.projects.mutate({headers, payload: {type: "project.update", commandId: CommandId.make(`track-${entry.id}`), projectId: entry.id, trackFolders: [{path: repository, name: "library"}]}});
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  await stage("original\nfirst\n");
  await browser.addInitScript(() => {
    const active = new Set<string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const m of [JSON.parse(data)].flat()) {
        if (m._tag === "Request" && m.tag === "subscribeVcsStatus" && m.payload.cwd.endsWith("/library")) {
          active.add(String(m.id));
          document.documentElement.dataset.librarySubscriptions = String(active.size);
        }
      }
      return send.call(this, data);
    };
    const listen = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(type, listener, options) {
      if (type === "message" && typeof listener === "function") {
        return listen.call(this, type, function(event: Event) {
          const data = (event as MessageEvent).data;
          if (typeof data === "string") for (const m of [JSON.parse(data)].flat()) {
            if (m._tag === "Exit" && active.delete(String(m.requestId))) document.documentElement.dataset.librarySubscriptions = String(active.size);
          }
          listener.call(this, event);
        }, options);
      }
      return listen.call(this, type, listener, options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  await t3.open();
  await browser.locator("[data-draft-project-trigger]").filter({hasText: "demo"}).waitFor();
  const toggle = screen.getByRole("button", "Toggle thread details panel", {exact: true});
  const other = screen.getByRole("button", "Other repositories...", {exact: true});
  if ((await toggle.getAttribute("aria-pressed")) !== "true") await toggle.tap();
  await other.tap();
  await screen.getByRole("menuitem", "library", {exact: true}).tap();
  const row = screen.getByRole("group", "Repository library", {exact: true}).getByRole("button").first();
  await row.getByText("+1", {exact: true}).waitFor();
  await app.screenshot("initial-one-staged-insertion");
  await row.tap();
  await toggle.tap();
  await browser.locator('html[data-library-subscriptions="0"]').waitFor({timeout: 45_000});
  await stage("original\nfirst\nsecond\n");
  const git = await runPromise(run("git", ["diff", "--cached", "--numstat"], {cwd: repository}));
  if (git.stdout.trim() !== "2\t0\tsource.txt") throw new Error("Expected two staged insertions");
  await toggle.tap();
  await row.waitFor();
  await browser.locator('html[data-library-subscriptions="1"]').waitFor();
  // Capture the reopened row after the server's initial response has rendered.
  await row.getByText("main", {exact: true}).waitFor();
  await app.screenshot("reopened-current-staged-count");
  await expect(row).toContainText("+2");
});
