import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { RequestsStore } from "../requests/requests-store";
import { createGithubChecksAdapter } from "./github-checks";

const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true }); });
function store(): RequestsStore { const root = mkdtempSync(join(tmpdir(), "overdeck-github-checks-")); roots.push(root); return new RequestsStore(join(root, "requests.sqlite")); }
function fakeGithub() {
  const calls: string[] = [];
  const fetchImpl = async (input: string | URL | Request) => {
    const url = String(input); calls.push(url);
    if (url.includes("/actions/runs")) return Response.json({ workflow_runs: [{ head_sha: "abc123", head_branch: "wt/arc-ci" }] });
    return Response.json({ check_runs: [{ id: 42, name: "collector-tests", status: "completed", conclusion: "success", head_sha: "abc123", started_at: "2026-08-16T10:00:00Z", completed_at: "2026-08-16T10:01:00Z" }] });
  };
  return { calls, fetchImpl };
}

describe("github-checks adapter", () => {
  test("ingests check events and deduplicates repeated polls by run id", async () => {
    const requests = store(); const github = fakeGithub();
    const adapter = createGithubChecksAdapter({ repo: "owner/overdeck", token: "secret", requests, fetchImpl: github.fetchImpl, now: () => Date.parse("2026-08-16T10:02:00Z") });
    await adapter.poll(); await adapter.poll();
    expect(requests.listGithubChecks()).toEqual([expect.objectContaining({ repo: "owner/overdeck", run_id: 42, name: "collector-tests", status: "completed", conclusion: "success", sha: "abc123", started_at: "2026-08-16T10:00:00Z", completed_at: "2026-08-16T10:01:00Z" })]);
    expect(github.calls).toHaveLength(4); requests.close();
  });
  test("maps a check SHA to the request work key", async () => {
    const requests = store();
    requests.create({ id: "work-arc-ci", title: "ARC CI", project: "overdeck", state: "in_flight", priority: "HIGH", asked_at: "2026-08-16T09:00:00Z", updated_at: "2026-08-16T09:00:00Z", detail: "Implement commit abc123" });
    const github = fakeGithub(); await createGithubChecksAdapter({ repo: "owner/overdeck", token: "secret", requests, fetchImpl: github.fetchImpl }).poll();
    expect(requests.listGithubChecks()[0]?.work_key).toBe("work-arc-ci"); requests.close();
  });
  test("retains unmatched checks for board visibility", async () => {
    const requests = store(); const github = fakeGithub();
    const result = await createGithubChecksAdapter({ repo: "owner/overdeck", token: "secret", requests, fetchImpl: github.fetchImpl }).poll();
    expect(requests.listGithubChecks()[0]).toMatchObject({ run_id: 42, work_key: null });
    expect(result.panels[0]?.data).toMatchObject({ checks: [expect.objectContaining({ run_id: 42, work_key: null })] }); requests.close();
  });
});
