import { execFileSync } from "node:child_process";
import { ProjectId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Linear uploaded images render in descriptions and comments", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Linear image proof");
  const projectId = execFileSync("sqlite3", ["-readonly", `${T3_HOME}/userdata/statev2.sqlite`, "SELECT project_id FROM projection_projects WHERE title = 'Linear image proof' AND deleted_at IS NULL LIMIT 1"], { encoding: "utf8" }).trim();
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["issueTrackers.connect"]({ tracker: "linear", token: process.env.LINEAR_API_KEY! });
    yield* client["issueTrackers.bindProject"]({ projectId: ProjectId.make(projectId), binding: { tracker: "linear", scope: "T3CF" } });
  }).pipe(Effect.scoped));
  await t3.open("/issues?host=linear.app&q=Image%20upload%20proof%2039085%20evidence-1");
  await screen.getByRole("button", /T3CF-20/).tap();
  await screen.getByText("Synthetic comment upload.", { exact: false }).waitFor();
  await browser.evaluate(async () => {
    await new Promise<void>((resolve) => {
      const check = () => {
        const alts = ["description upload", "comment upload"];
        if (alts.every((alt) => {
          const img = document.querySelector<HTMLImageElement>(`img[alt="${alt}"]`);
          return img?.complete || [...document.querySelectorAll("span")].some((el) => el.textContent?.includes(`Image unavailable`) && el.textContent?.includes(alt));
        })) resolve();
        else setTimeout(check, 100);
      };
      check();
      setTimeout(resolve, 10000);
    });
  });
  await app.screenshot("linear-description");
  await browser.evaluate(() => {
    const text = [...document.querySelectorAll("p")].find((el) => el.textContent === "Synthetic comment upload.");
    text?.scrollIntoView({ block: "start", behavior: "instant" });
  });
  await app.screenshot("linear-comment");
  await expect.poll(() => browser.evaluate(() =>
    ["description upload", "comment upload"].every((alt) => {
      const img = document.querySelector<HTMLImageElement>(`img[alt="${alt}"]`);
      return img !== null && img.complete && img.naturalWidth === 640 && img.naturalHeight === 240;
    })
  )).toBe(true);
});
