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

async function linear(query: string, variables: Record<string, unknown> = {}) {
  const response = await fetch("https://api.linear.app/graphql", {
    method: "POST",
    headers: { Authorization: process.env.LINEAR_API_KEY!, "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  const result = await response.json();
  if (result.errors) throw new Error(JSON.stringify(result.errors));
  return result.data;
}

test("Unsent issue comments survive switching and closing panels", WEB, async ({ t3, app, browser, screen }) => {
  const created: string[] = [];
  try {
    const issues = [];
    for (const name of ["A", "B"]) {
      const data = await linear('mutation($input: IssueCreateInput!) { issueCreate(input:$input) { issue { id identifier title } } }', {
        input: { teamId: process.env.LINEAR_TEST_TEAM_ID, title: `Draft proof 46405 ${name}` },
      });
      issues.push(data.issueCreate.issue);
      created.push(data.issueCreate.issue.id);
    }
    const project = await t3.project("Comment draft proof");
    const thread = await t3.thread({ project, title: "Draft proof", messages: ["first"] });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) });
      yield* client["issueTrackers.connect"]({ tracker: "linear", token: process.env.LINEAR_API_KEY! });
      yield* client["issueTrackers.bindProject"]({ projectId: projection.thread.projectId, binding: { tracker: "linear", scope: process.env.LINEAR_TEST_TEAM_KEY! } });
    }).pipe(Effect.scoped));
    await browser.setViewport({ width: 1440, height: 1000 });
    await t3.open("/issues?host=linear.app&q=Draft%20proof%2046405");
    const a = screen.getByText(issues[0].title, { exact: true });
    const b = screen.getByText(issues[1].title, { exact: true });
    const composer = screen.getByRole("textbox", "Add a comment", { exact: true });
    await a.tap();
    await composer.fill("Unsent draft for issue A - do not lose me");
    await app.screenshot("draft-before-navigation");
    await b.tap();
    await composer.fill("Different draft for issue B");
    await a.tap();
    await app.screenshot("issue-a-after-switch");
    const restoredA = await browser.evaluate(() => (document.querySelector('textarea[aria-label="Add a comment"]') as HTMLTextAreaElement)?.value);
    await composer.fill("Second draft for A before closing panel");
    await screen.getByRole("button", `Close ${issues[0].identifier}`, { exact: false }).tap();
    await a.tap();
    await app.screenshot("issue-a-after-reopen");
    const reopenedA = await browser.evaluate(() => (document.querySelector('textarea[aria-label="Add a comment"]') as HTMLTextAreaElement)?.value);
    await b.tap();
    await app.screenshot("issue-b-after-switch");
    const restoredB = await browser.evaluate(() => (document.querySelector('textarea[aria-label="Add a comment"]') as HTMLTextAreaElement)?.value);
    expect({ restoredA, reopenedA, restoredB }).toEqual({ restoredA: "Unsent draft for issue A - do not lose me", reopenedA: "Second draft for A before closing panel", restoredB: "Different draft for issue B" });
  } finally {
    for (const id of created) await linear('mutation($id:String!) { issueDelete(id:$id) { success } }', { id });
  }
});
