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

const repository = "julius54/proof-linked-row-48696-1204";
const url = `https://gitlab.com/${repository}/-/merge_requests/1`;
const edit = (title: string, target: string) => runPromise(run("glab", ["api", "-X", "PUT", "projects/89861279/merge_requests/1", "-f", `title=${title}`, "-f", `target_branch=${target}`, "--silent"]));

test("Linked row and composer payload follow the real GitLab detail", WEB, async ({t3, app, browser, screen}) => {
  await edit("Old MR title", "main");
  const project = await t3.project("Linked MR proof");
  await runPromise(run("git", ["remote", "add", "origin", `https://gitlab.com/${repository}.git`], {cwd: project}));
  const thread = await t3.thread({project, title: "Linked merge request", messages: ["Start"], model: "multi-turn"});
  const threadId = ThreadId.make(thread.threadId);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const {thread: projection} = yield* client["orchestration.getThreadProjection"]({threadId});
    const ref = {projectId: projection.projectId, host: "gitlab.com", repository, number: 1};
    const detail = yield* client["pullRequests.detail"]({...ref, allowStale:false});
    const key = {threadId, host: ref.host, repository, number: 1};
    yield* client["orchestration.dispatchCommand"]({type:"thread.pull-request.link", commandId:CommandId.make(`${thread.threadId}-link`), ...key, url, source:"manual"});
    yield* client["orchestration.dispatchCommand"]({type:"thread.pull-request-link.sync", commandId:CommandId.make(`${thread.threadId}-sync`), ...key, snapshot:{state:detail.state,title:detail.title,headBranch:detail.headBranch,baseBranch:detail.baseBranch,isDraft:detail.isDraft ?? false,updatedAt:detail.updatedAt,syncedAt:new Date().toISOString(),author:detail.author,additions:detail.additions,deletions:detail.deletions}, stack:null});
  }).pipe(Effect.scoped));
  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", "Linked items L", {exact:true}).tap();
  await screen.getByRole("link", /^#1 Old MR title/).waitFor();
  await app.screenshot("initial-saved-row");
  await edit("Updated MR title", "develop");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const {thread: projection} = yield* client["orchestration.getThreadProjection"]({threadId});
    yield* client["pullRequests.invalidate"]({reference:{projectId:projection.projectId,host:"gitlab.com",repository,number:1}});
  }).pipe(Effect.scoped));
  await screen.getByRole("link", /^#1 Old MR title/).tap();
  await screen.getByRole("heading", "Updated MR title", {exact:true}).waitFor();
  await app.screenshot("new-detail");
  await screen.getByRole("button", "Linked items", {exact:true}).tap();
  const row = screen.getByRole("link", /^#1 /);
  await row.waitFor();
  const observed = await browser.evaluate(() => {
    const a = [...document.querySelectorAll("a")].find(a => a.textContent?.includes("#1") && a.href.includes("/-/merge_requests/1"));
    const draggable = a?.closest('[draggable="true"]') ?? a;
    const transfer = new DataTransfer();
    draggable?.dispatchEvent(new DragEvent("dragstart", {bubbles:true,dataTransfer:transfer}));
    return {row:a?.parentElement?.textContent,payload:transfer.getData("application/x-t3code-pull-request")};
  });
  console.log("OBSERVED_LINKED_MR " + JSON.stringify(observed));
  await app.screenshot("linked-row-after-detail");
  expect(observed.row).toContain("Updated MR title");
  expect(observed.row).toContain("develop");
  expect(observed.payload).toContain("Updated MR title");
  expect(observed.payload).toContain("develop");
});
