import { readFileSync, symlinkSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const host = process.env.PROOF_FORGEJO_URL!;
const token = readFileSync(process.env.PROOF_TOKEN_FILE!, "utf8").trim();
async function api(path: string, method = "GET", body?: unknown) {
  const response = await fetch(`${host}/api/v1/${path}`, {
    method, headers: { Authorization: `token ${token}`, "Content-Type": "application/json" },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  const text = await response.text();
  if (!response.ok) throw new Error(`${method} ${path}: ${response.status} ${text}`);
  return text ? JSON.parse(text) : null;
}

test("Forgejo schedules, cancels and squash-merges after required checks pass", WEB, async ({ t3, app, screen, browser }) => {
  symlinkSync(process.env.PROOF_TEA_BINARY!, join(T3_HOME, "bin", "tea"));
  const name = `auto-merge-${Date.now()}`;
  const repo = `scenario/${name}`;
  await api("user/repos", "POST", { name, auto_init: true, default_branch: "main", private: false });
  await api(`repos/${repo}`, "PATCH", { allow_squash_merge: true, default_merge_style: "squash", default_delete_branch_after_merge: true });
  await api(`repos/${repo}/branches`, "POST", { new_branch_name: "feature", old_branch_name: "main" });
  const content = await api(`repos/${repo}/contents/feature.txt`, "POST", { branch: "feature", content: Buffer.from("Ready after checks\n").toString("base64"), message: "Add feature" });
  const sha = content.commit.sha;
  await api(`repos/${repo}/branch_protections`, "POST", { rule_name: "main", enable_push: true, enable_status_check: true, status_check_contexts: ["proof/check"], apply_to_admins: true });
  await api(`repos/${repo}/statuses/${sha}`, "POST", { state: "pending", context: "proof/check", description: "Waiting for required check" });
  const pr = await api(`repos/${repo}/pulls`, "POST", { base: "main", head: "feature", title: "Squash after required checks", body: "Synthetic Forgejo auto-merge proof." });
  const project = await t3.project("Forgejo demo");
  execFileSync("git", ["remote", "add", "origin", `${host}/${repo}.git`], { cwd: project });
  const thread = await t3.thread({ project, title: "Forgejo auto-merge", messages: ["first"] });
  await t3.open(thread);
  await t3.open("/pull-requests");
  await screen.getByRole("button", repo, { exact: false }).tap();
  await screen.getByRole("button", "More pull request actions").tap();
  await screen.getByRole("menuitemradio", "Squash and merge").tap();
  await screen.getByRole("button", "More pull request actions").tap();
  await app.screenshot("auto-merge-action");
  await browser.keyboard.press("Escape");
  await expect(screen.getByRole("button", "Auto-merge (squash and merge)", { exact: true })).toBeVisible();
  await screen.getByRole("button", "Auto-merge (squash and merge)", { exact: true }).tap();
  await screen.getByRole("button", "Confirm auto-merge?", { exact: true }).tap();
  await expect(screen.getByRole("img", "Auto-merge", { exact: true })).toBeVisible();
  await expect.poll(async () => (await api(`repos/${repo}/issues/1/timeline`)).filter((event: { type: string }) => event.type === "pull_scheduled_merge").length).toBe(1);
  await screen.getByRole("button", "More pull request actions").tap();
  await screen.getByRole("menuitem", "Refresh", { exact: true }).tap();
  await expect(screen.getByRole("img", "Auto-merge", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "More pull request actions")).toBeVisible();
  await app.screenshot("scheduled");
  await screen.getByRole("button", "More pull request actions").tap();
  await expect(screen.getByRole("menuitem", "Disable auto-merge", { exact: true })).toBeVisible();
  await screen.getByRole("menuitem", "Disable auto-merge", { exact: true }).tap();
  await expect.poll(async () => (await api(`repos/${repo}/issues/1/timeline`)).at(-1).type).toBe("pull_cancel_scheduled_merge");
  await expect(screen.getByRole("button", "Auto-merge (squash and merge)", { exact: true })).toBeVisible();
  await expect(screen.getByRole("button", "Auto-merge (squash and merge)", { exact: true })).toBeEnabled();
  await app.screenshot("cancelled");
  await screen.getByRole("button", "Auto-merge (squash and merge)", { exact: true }).tap();
  await screen.getByRole("button", "Confirm auto-merge?", { exact: true }).tap();
  await expect(screen.getByRole("img", "Auto-merge", { exact: true })).toBeVisible();
  await expect.poll(async () => (await api(`repos/${repo}/issues/1/timeline`)).filter((event: { type: string }) => event.type === "pull_scheduled_merge").length).toBe(2);
  await api(`repos/${repo}/statuses/${sha}`, "POST", { state: "success", context: "proof/check", description: "Required check passed" });
  await expect.poll(async () => (await api(`repos/${repo}/pulls/1`)).merged, { timeout: 60000 }).toBe(true);
  await screen.getByRole("button", "More pull request actions").tap();
  await screen.getByRole("menuitem", "Refresh", { exact: true }).tap();
  await expect(screen.getByText("Merged", { exact: true }).first()).toBeVisible({ timeout: 60000 });
  await expect(screen.getByRole("button", "More pull request actions")).toBeVisible();
  await app.screenshot("merged");
});
