import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { readFile } from "node:fs/promises";
import { test, WEB, makeState, rpcClient, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Qualified Linear numbers only match their named team", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Linear search proof");
  const runtime = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]));
  const snapshot = await fetch(`${runtime.origin}/api/projects`, {headers:{authorization:`Bearer ${issued.stdout.trim()}`}}).then(r=>r.json());
  await runPromise(Effect.scoped(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, runtime.origin);
    yield* rpc["issueTrackers.connect"]({tracker:"linear",token:process.env.LINEAR_API_KEY!});
    yield* rpc["issueTrackers.bindProject"]({projectId:snapshot.projects[0].id,binding:{tracker:"linear",scope:process.env.LINEAR_TEST_TEAM_KEY!}});
  })));
  await t3.open("/issues?status=all&who=all&q=T3CF-237");
  const search = screen.getByRole("searchbox", "Search issues");
  await screen.getByText("pr39809-proof: unrelated issue (no other team text)", {exact:true}).waitFor({state:"visible"});
  await app.screenshot("matching-team-control");
  const find = async (query: string, label: string) => {
    await search.fill(query);
    await browser.locator('[data-slot="input-group"] [aria-label="Loading"]').waitFor({state:"visible"});
    await browser.locator('[data-slot="input-group"] [aria-label="Loading"]').waitFor({state:"hidden"});
    await app.screenshot(label);
  };
  await find("237", "bare-number-control");
  await find("#237", "hash-number-control");
  await find("ENG-1", "text-match-control");
  await find("ENG-999", "absent-number-control");
  await find("OTHER-237", "other-team-search");
  await find("ENG-237", "foreign-team-search");
  await expect(screen.getByText("pr39809-proof: unrelated issue (no other team text)", {exact:true})).not.toBeVisible();
});
