/// <reference lib="dom" />
import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, IssueTrackerKind } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Private Linear images load and description drafts survive refresh", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = JSON.parse(process.env.LINEAR_EVIDENCE_FIXTURE!);
  const graph = async (query: string, variables: unknown) => {
    const response = await fetch("https://api.linear.app/graphql", { method: "POST", headers: { "Content-Type": "application/json", Authorization: process.env.LINEAR_API_KEY! }, body: JSON.stringify({ query, variables }) });
    const result = await response.json();
    if (result.errors) throw new Error("Linear fixture request failed");
    return result.data;
  };
  await graph('mutation($id:String!,$input:IssueUpdateInput!){issueUpdate(id:$id,input:$input){success}}', { id: fixture.id, input: { description: `Private image in description\n\n![Description screenshot](${fixture.assetUrl})` } });
  await browser.addInitScript(() => {
    const state = { bodies: [] as string[], completed: Promise.resolve() };
    Object.assign(window, { linearEvidence: state });
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const request = typeof data === "string" ? JSON.parse(data) : null;
      if (request?._tag === "Request" && request.tag === "issues.detail") {
        state.completed = new Promise<void>((resolve) => {
          const listener = (event: MessageEvent) => {
            for (const message of [JSON.parse(event.data)].flat()) {
              if (message._tag === "Exit" && String(message.requestId) === String(request.id)) {
                if (message.exit?._tag === "Success") state.bodies.push(message.exit.value.body);
                this.removeEventListener("message", listener);
                resolve();
              }
            }
          };
          this.addEventListener("message", listener);
        });
      }
      return send.call(this, data);
    };
  });
  const project = await t3.project("linear-evidence");
  const thread = await t3.thread({ project, title: "Private issue images", messages: ["Review the linked issue screenshots."] });
  const ref = await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
    const projection = yield* rpc["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) });
    const projectId = projection.thread.projectId;
    yield* rpc["issueTrackers.connect"]({ tracker: IssueTrackerKind.make("linear"), token: process.env.LINEAR_API_KEY! });
    yield* rpc["issueTrackers.bindProject"]({ projectId, binding: { tracker: IssueTrackerKind.make("linear"), scope: "T3CF" } });
    const issue = { projectId, tracker: IssueTrackerKind.make("linear"), scope: "T3CF", key: fixture.identifier };
    yield* rpc["orchestration.dispatchCommand"]({ type: "thread.issue.link", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(thread.threadId), ...issue, host: "linear.app", url: fixture.url, displayKey: fixture.identifier, title: fixture.title, source: "manual" });
    return issue;
  })));
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  // Open the linked issue using its real issue route after opening its owning thread.
  await t3.open(`/issues?selectedProjectId=${ref.projectId}&tracker=linear&scope=T3CF&key=${fixture.identifier}`);
  await screen.getByRole("button", "Edit description", { exact: true }).waitFor({ timeout: 60_000 });
  await expect.soft(browser.locator('img[alt="Description screenshot"]')).toBeVisible();
  await app.screenshot("private-description");
  await browser.evaluate(() => { [...document.querySelectorAll("p")].find(el => el.textContent === "Newest page screenshot")?.scrollIntoView({ block: "center" }); return null; });
  await expect.soft(browser.locator('img[alt="Newest screenshot"]')).toBeVisible();
  await app.screenshot("private-latest-comment");
  await screen.getByRole("button", "Load older comments", { exact: true }).tap();
  await screen.getByText("Older page screenshot", { exact: true }).waitFor();
  await browser.evaluate(() => { [...document.querySelectorAll("p")].find(el => el.textContent === "Older page screenshot")?.scrollIntoView({ block: "center" }); return null; });
  await expect.soft(browser.locator('img[alt="Comment screenshot"]').first()).toBeVisible();
  await app.screenshot("private-older-comment");
  await screen.getByRole("button", "Edit description", { exact: true }).tap();
  const editor = screen.getByRole("textbox", "Description", { exact: true });
  const original = await browser.evaluate(() => document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Description"]')?.value ?? "");
  const beforeRefreshBody = await browser.evaluate(() => (window as unknown as { linearEvidence: { bodies: string[] } }).linearEvidence.bodies.at(-1) ?? "");
  await editor.fill(original + "\n\nUnsaved description draft survives refresh.");
  await screen.getByRole("button", "Refresh issue", { exact: true }).tap();
  const renewal = await browser.evaluate(async (before) => {
    const state = (window as unknown as { linearEvidence: { bodies: string[], completed: Promise<void> } }).linearEvidence;
    await state.completed;
    const signed = state.bodies.filter(body => body.includes("signature="));
    const after = state.bodies.at(-1) ?? "";
    const stable = (body: string) => body.replace(/([?&])signature=[^\s)&#]+/g, "");
    return { signedBodiesObserved: signed.length, signatureRenewedOnRefresh: before.includes("signature=") && after !== before, onlySignatureChanged: after !== before && stable(after) === stable(before) };
  }, beforeRefreshBody);
  await expect(screen.getByRole("button", "Refresh issue", { exact: true })).toBeEnabled();
  await screen.getByRole("button", "Preview", { exact: true }).tap();
  await app.screenshot("description-draft-after-refresh");
  await expect(screen.getByText("Unsaved description draft survives refresh.", { exact: true })).toBeVisible();
  await screen.getByRole("button", "Save", { exact: true }).tap();
  await screen.getByRole("button", "Edit description", { exact: true }).waitFor();
  await screen.getByRole("button", "Edit description", { exact: true }).tap();
  await expect(editor).toHaveValue(/Unsaved description draft survives refresh\./);
  await screen.getByRole("button", "Preview", { exact: true }).tap();
  await app.screenshot("saved-description-reopened");
  const saved = await graph('query($id:String!){issue(id:$id){description}}', { id: fixture.id });
  const metrics = { ...renewal, savedDescriptionHasSignature: saved.issue.description.includes("signature="), savedEditPresent: saved.issue.description.includes("Unsaved description draft survives refresh.") };
  writeFileSync(`${process.env.LINEAR_EVIDENCE_OUTPUT}/metrics-${Date.now()}.json`, JSON.stringify(metrics));
});
