import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schedule from "effect/Schedule";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.ts";

const DEFINITION = `const { workflow, subject, title, skip, ask, step, start } = T3;
const about = workflow("about", { version: 1, payload: Schema.Struct({ skip: Schema.Boolean, n: Schema.Number }) }, Effect.fn(function* (payload) {
  yield* subject("https://github.com/pingdotgg/t3code/issues/43730");
  if (payload.skip) { yield* title("Skipped duplicate " + payload.n); return yield* skip("duplicate"); }
  yield* title("Triage issue 43730");
  yield* ask("approve", { title: "Approve the triage fix?", choices: ["Yes", "No"] });
}));
const flood = workflow("flood", { version: 1, payload: Schema.Struct({ count: Schema.Number }) }, () =>
  step("spawn", { returns: Schema.Number }, Effect.gen(function* () {
    for (let n = 1; n <= 500; n++) yield* start(about, { skip: true, n }, { key: "skip-" + n });
    return 500;
  })));
export default [about, flood];`;

const waitUntil = async <A>(read: () => Promise<A>, ready: (value: A) => boolean) =>
  runPromise(Effect.tryPromise({ try: read, catch: (error) => error }).pipe(
    Effect.flatMap((value) => ready(value) ? Effect.succeed(value) : Effect.fail(new Error("seed not ready"))),
    Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 240 }),
  ));

test("Issue keeps its waiting run and question after 500 newer skipped runs", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("t3code");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: workspace }));
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const issued = await cli(["auth", "session", "issue", "--token-only"]);
  const projects = await fetch(`${app.baseUrl}/api/projects`, { headers: { authorization: `Bearer ${issued.stdout.trim()}` } }).then((r) => r.json());
  const projectId = projects.projects.find((p: {title: string}) => p.title === "t3code").id;
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/about.ts`, DEFINITION);
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
  }).pipe(Effect.scoped));
  const waiting = await waitUntil(() => cli(["workflow", "start", "about", "--input", '{"skip":false,"n":0}', "--key", "waiting", "--json"]), () => true);
  const runId = JSON.parse(waiting.stdout).run.runId;
  await waitUntil(async () => JSON.parse((await cli(["workflow", "show", runId, "--json"])).stdout), (value) => value.run.status === "waiting");
  await cli(["workflow", "start", "flood", "--input", '{"count":500}', "--key", "flood", "--json"]);
  await waitUntil(async () => JSON.parse((await cli(["workflow", "list", "--status", "skipped", "--json"])).stdout), (value) => value.length === 500);
  const questions = JSON.parse((await cli(["workflow", "questions", "--json"])).stdout);
  if (!JSON.stringify(questions).includes("Approve the triage fix?")) throw new Error("The waiting question was not seeded");

  await t3.open(`/issues?status=all&selectedProjectId=${projectId}&tracker=github&scope=pingdotgg%2Ft3code&key=43730`);
  await screen.getByRole("heading", "Workflow runs", { exact: true }).waitFor({ timeout: 60_000 });
  await browser.locator('button[aria-label="Refresh issues"]:disabled').waitFor({ state: "hidden", timeout: 60_000 });
  await app.screenshot("issue-workflow-runs");
  await expect(screen.getByText("Triage issue 43730", { exact: true })).toBeVisible();
  await expect(screen.getByText("Approve the triage fix?", { exact: true })).toBeVisible();
});
