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

test("A failed GitLab page stays under GitLab while Linear loads its next page", WEB, async ({ t3, app, browser }) => {
  await browser.setViewport({ width: 1440, height: 1000 });
  const seed = await t3.project("pagination-seed");
  const repository = `${T3_HOME}/pagination-repository`;
  await runPromise(run("git", ["clone", "--quiet", seed, repository]));
  await runPromise(run("git", ["remote", "set-url", "origin", "https://gitlab.com/gitlab-org/cli.git"], { cwd: repository }));
  const state = makeState(T3_HOME);
  await runPromise(state.cli(["project", "add", repository, "--title", "Pagination proof"]));
  try {
    const origin = app.baseUrl ?? "";
    const auth = await runPromise(state.cli(["auth", "session", "issue", "--token-only"]));
    const snapshot = await (await fetch(`${origin}/api/projects`, { headers: { Authorization: `Bearer ${auth.stdout.trim()}` } })).json();
    const project = snapshot.projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === repository);
    if (!project) throw new Error("The proof project was not registered");
    await runPromise(Effect.gen(function* () {
      const rpc = yield* rpcClient(T3_HOME, origin);
      yield* rpc["issueTrackers.connect"]({ tracker: IssueTrackerKind.make("linear"), token: process.env.LINEAR_API_KEY! });
      yield* rpc["issueTrackers.bindProject"]({ projectId: ProjectId.make(project.id), binding: { tracker: IssueTrackerKind.make("linear"), scope: process.env.LINEAR_TEST_TEAM_KEY! } });
    }).pipe(Effect.scoped));
    // Send a real invalid continuation to the server, preserving all genuine service replies.
    await browser.addInitScript(() => {
      const send = WebSocket.prototype.send;
      let rejected = false;
      Object.assign(window, { paginationRequests: [] });
      WebSocket.prototype.send = function(data) {
        if (typeof data === "string") {
          const request = JSON.parse(data);
          if (request._tag === "Request" && request.tag === "issues.list" && Object.keys(request.payload.cursors ?? {}).length) {
            const keys = Object.keys(request.payload.cursors);
            (window as unknown as { paginationRequests: unknown[] }).paginationRequests.push(keys);
            if (!rejected && keys.every(k => k.startsWith("gitlab.com "))) {
              rejected = true;
              request.payload.limit = 201;
              data = JSON.stringify(request);
            }
          }
        }
        return send.call(this, data);
      };
    });
    await t3.open("/issues");
    const gitlab = browser.locator('section').filter({ has: browser.locator('h2').filter({ hasText: 'GitLab' }) });
    const linear = browser.locator('section').filter({ has: browser.locator('h2').filter({ hasText: 'Linear' }) });
    await gitlab.getByRole("button", { name: "Load more", exact: true }).waitFor({ timeout: 120000 });
    await linear.getByRole("button", { name: "Load more", exact: true }).waitFor({ timeout: 120000 });
    await gitlab.getByRole("button", { name: "Load more", exact: true }).click();
    await gitlab.getByRole("button", { name: "Retry", exact: true }).waitFor();
    await app.screenshot("gitlab-after-rejected-continuation");
    const linearButton = linear.getByRole("button", { name: /^(Load more|Retry)$/, exact: true });
    await linearButton.scrollIntoView();
    const linearLabelAfterFailure = await linearButton.textContent();
    await app.screenshot("linear-after-gitlab-failure");
    await linearButton.click();
    const nextLinearIssue = linear.getByRole("button", { name: /Pagination proof 45741 a1796013291 — item 01/ });
    await nextLinearIssue.waitFor({ timeout: 60000 });
    await nextLinearIssue.scrollIntoView();
    await app.screenshot("linear-after-successful-continuation");
    const gitlabButton = gitlab.getByRole("button", { name: /^(Load more|Retry)$/, exact: true });
    await gitlabButton.scrollIntoView();
    const gitlabLabelAfterLinearSuccess = await gitlabButton.textContent();
    await app.screenshot("gitlab-after-linear-success");
    expect(linearLabelAfterFailure?.trim()).toBe("Load more");
    expect(gitlabLabelAfterLinearSuccess?.trim()).toBe("Retry");
  } finally {
    await runPromise(state.cli(["project", "remove", repository, "--force"]));
  }
});
