import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { readControllerSource } from "./controller";

const FIXTURE_PATH = join(import.meta.dir, "../../../test/fixtures/activity/controller.jsonl");

describe("readControllerSource", () => {
  test("maps controller records into stable activity events", () => {
    const fixture = readFileSync(FIXTURE_PATH, "utf8");
    const options = {
      path: FIXTURE_PATH,
      readFileImpl: () => fixture,
      fromMs: Date.parse("2026-08-01T00:00:00.000Z"),
      toMs: Date.parse("2026-08-01T23:59:59.999Z"),
    };

    const { coverage, events } = readControllerSource(options);

    expect(coverage).toEqual({
      id: "controller",
      label: "controller events",
      category: "buildbox",
      path: FIXTURE_PATH,
      status: "ok",
      records: 2,
      totalRecords: 3,
      skipped: 1,
      earliest: "2026-07-31T23:45:00.000Z",
      latest: "2026-08-01T01:20:00.000Z",
    });

    expect(events).toHaveLength(2);
    expect(events.map((event) => event.id)).toEqual(["controller:1", "controller:4"]);

    expect(events.at(0)).toMatchObject({
      id: "controller:1",
      category: "buildbox",
      source: "controller",
      actor: "system",
      ts: "2026-08-01T00:10:00.000Z",
      project: "multideal",
      host: "debian1",
      session: "job-in-range-1",
      durationMs: 1500,
      rc: 2,
      severity: "error",
      dedupeKey: "debian1:gate-run:failed",
      title: "debian1 · multideal · gate-run — failed",
      detail: {
        ts: "2026-08-01T00:10:00.000Z",
        job: "job-in-range-1",
        repo: "multideal",
        host: "debian1",
        snapshot: "a",
        attempt: 1,
        stage: "gate-run",
        reason: "failed",
        rc: 2,
        durationSeconds: 1.5,
      },
    });

    expect(events.at(1)).toMatchObject({
      id: "controller:4",
      ts: "2026-08-01T01:20:00.000Z",
      project: "multideal",
      host: "debian1",
      session: "job-in-range-2",
      durationMs: 5000,
      severity: "info",
      title: "debian1 · multideal · deploy",
    });
    expect((events.at(1) as { rc?: number }).rc).toBeUndefined();
  });

  test("reports absent when controller file does not exist", () => {
    const { coverage, events } = readControllerSource({
      path: "/tmp/no-such-file",
      existsSyncImpl: () => false,
    });

    expect(events).toEqual([]);
    expect(coverage).toEqual({
      id: "controller",
      label: "controller events",
      category: "buildbox",
      path: "/tmp/no-such-file",
      status: "absent",
      records: 0,
      totalRecords: 0,
      skipped: 0,
    });
  });
});
