import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { ProjectSnapshot } from "@t3tools/contracts";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { writeFile } from "node:fs/promises";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.ts";

test("A PR referenced by a run about another PR shows its waiting run and question", WEB,
async ({ t3, app, screen }) => {
  const workspace = await t3.project("Workflow proof");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: workspace }));
  const origin = app.baseUrl!;
  const environment = await runPromise(environmentId(origin));
  const project = await runPromise(Effect.gen(function* () {
    const { stdout } = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const { projects } = yield* HttpClient.execute(HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(stdout.trim()))).pipe(
      Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
    return projects.find(p => p.workspaceRoot === workspace)!;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.makeDirectory(`${T3_HOME}/workflows`, { recursive: true });
    yield* fs.writeFileString(`${T3_HOME}/workflows/reference-proof.ts`, `export default T3.workflow("reference-proof", { version: 1, payload: Schema.Struct({ project: Schema.String }) },
      Effect.fn(function* (payload) {
        yield* T3.title("Working on linked pull request");
        yield* T3.subject("https://github.com/pingdotgg/t3code/pull/46768");
        yield* T3.step("Read linked PR", { returns: Schema.String },
          T3.pullRequests.read({ project: payload.project, url: "https://github.com/pingdotgg/t3code/pull/46800" }).pipe(Effect.map(pr => pr.title)));
        yield* T3.ask("review", { title: "Ready to review the linked pull request?", choices: ["Review", "Wait"] });
      }));`);
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["server.updateSettings"]({ patch: { workflowsEnabled: true } });
    yield* makeState(T3_HOME).cli(["workflow", "start", "reference-proof", "--key", "proof", "--input", JSON.stringify({ project: workspace })]);
  }).pipe(Effect.scoped));
  await t3.open("/workflows");
  await screen.getByText("Ready to review the linked pull request?", { exact: true }).first().waitFor();
  const listed = await runPromise(makeState(T3_HOME).cli(["workflow", "list", "--subject", "https://github.com/pingdotgg/t3code/pull/46800", "--json"]));
  const runs = JSON.parse(listed.stdout);
  await writeFile(new URL(`../.e2e/cli-${APP_DIR.includes("a681dd5d20") ? "base" : "head"}.json`, import.meta.url), JSON.stringify({
    command: "t3 workflow list --subject https://github.com/pingdotgg/t3code/pull/46800 --json",
    runs: runs.map((r: { title: string; status: string; subject: unknown }) => ({ title: r.title, status: r.status, subject: r.subject }))
  }, null, 2));
  const query = new URLSearchParams({ repository: "pingdotgg/t3code", number: "46800", selectedProjectId: project.id,
    selectedEnvironmentId: environment, selectedHost: "github.com" });
  await t3.open(`/pull-requests?${query}`);
  await screen.getByText("perf(mobile): tabs switch and threads open 2-3x faster, Android idle CPU down 79%", { exact: true }).first().waitFor();
  await screen.getByRole("status", /^Loading pull requests/).waitFor({ state: "hidden" });
  await app.screenshot("referenced-pr-workflow-run");
  await expect(screen.getByText("Working on linked pull request", { exact: true })).toBeVisible();
  await expect(screen.getByText("Ready to review the linked pull request?", { exact: true })).toBeVisible();
  expect(runs.some((r: { title: string }) => r.title === "Working on linked pull request")).toBe(true);
});
