import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { readFileSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

const graphql = async (query: string, variables = {}) => {
  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 body = await response.json();
  if (body.errors) throw new Error(JSON.stringify(body.errors));
  return body.data;
};
const sql = (query: string) => JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, query], { encoding: "utf8" }) || "[]");
const rpc = (origin: string, method: string, input: object) => runPromise(Effect.scoped(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, origin);
  return yield* (client as any)[method](input);
})));
const until = async (read: () => Promise<any>, ready: (value: any) => boolean, timeout = 160_000) => {
  const end = Date.now() + timeout;
  while (Date.now() < end) {
    const value = await read();
    if (ready(value)) return value;
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
  throw new Error("Workflow did not reach the expected runtime milestone");
};

test("Equivalent issue labels are rejected before duplicate runs start", WEB, async ({ t3, app, screen }) => {
  await t3.project("server");
  const [{ project_id: projectId }] = sql("SELECT project_id FROM projection_projects WHERE title = 'server' AND deleted_at IS NULL");
  const origin = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8")).origin;
  await rpc(origin, "server.updateSettings", { patch: { workflowsEnabled: true } });
  await rpc(origin, "issueTrackers.connect", { tracker: "linear", token: process.env.LINEAR_API_KEY });
  await rpc(origin, "issueTrackers.bindProject", { projectId, binding: { tracker: "linear", scope: process.env.LINEAR_TEST_TEAM_KEY } });
  const labels = await graphql('query { issueLabels(first: 250) { nodes { id name } } }');
  const docs = labels.issueLabels.nodes.find((label: any) => label.name === "docs");
  if (!docs) throw new Error("The existing docs label is unavailable");
  const files: any = await rpc(origin, "workflows.getDefinition", {});
  writeFileSync(`${files.directory}/triage.ts`, `const { workflow, issues, Issue, title } = T3;
export default workflow("triage", {
  version: 1, payload: Issue,
  triggers: [
    issues.opened({ project: ${JSON.stringify(projectId)}, labels: ["docs"] }),
    issues.opened({ project: ${JSON.stringify(projectId)}, labels: ["docs", "docs"] }),
  ],
}, Effect.fn(function* (issue) {
  yield* title("Triage " + issue.title);
  return { triaged: issue.url };
}));
`);
  const definitions: any = await until(() => rpc(origin, "workflows.getDefinition", {}), (value) => value.files.some((file: any) => file.name === "triage.ts"));
  const definition = definitions.files.find((file: any) => file.name === "triage.ts");
  if (definition.problems.length === 0) {
    await until(async () => sql("SELECT * FROM workflow_triggers"), (rows) => rows.length === 2);
  }
  let issueId: string | undefined;
  try {
    const created = await graphql('mutation($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { id identifier url } } }', {
      input: { teamId: process.env.LINEAR_TEST_TEAM_ID, title: "[pr-45276-proof] equivalent label filters", labelIds: [docs.id] },
    });
    issueId = created.issueCreate.issue.id;
    if (!created.issueCreate.success) throw new Error("Linear issue creation failed");
    if (definition.problems.length === 0) {
      await until(async () => sql("SELECT status FROM workflow_runs WHERE workflow = 'triage'"), (rows) => rows.length === 2 && rows.every((row: any) => row.status === "completed"));
      await t3.open("/workflows");
      await screen.getByRole("button", "All", { exact: true }).tap({ timeout: 120_000 });
      await screen.getByText("Triage [pr-45276-proof] equivalent label filters", { exact: true }).first().waitFor({ timeout: 120_000 });
    } else {
      await t3.open("/workflows?definitions=true&file=triage.ts");
      await screen.getByText('workflow("triage") lists the same trigger twice. List it once.', { exact: false }).first().waitFor({ timeout: 120_000 });
    }
    await app.screenshot("equivalent-label-trigger-outcome");
    await expect(definition.problems.map((problem: any) => problem.message).join("\n")).toContain('workflow("triage") lists the same trigger twice. List it once.');
  } finally {
    if (issueId) await graphql('mutation($id: String!) { issueDelete(id: $id) { success } }', { id: issueId });
  }
});
