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

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

describe("readActionsSource", () => {
  test("maps action audit records and skips malformed entries", () => {
    const fixture = readFileSync(FIXTURE_PATH, "utf8");
    const { coverage, events } = readActionsSource({
      path: FIXTURE_PATH,
      readFileImpl: () => fixture,
      fromMs: Date.parse("2026-08-01T00:00:00.000Z"),
      toMs: Date.parse("2026-08-01T23:59:59.999Z"),
    });

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

    expect(events).toHaveLength(2);
    expect(events).toEqual([
      expect.objectContaining({
        id: "actions:1",
        ts: "2026-08-01T00:10:00.000Z",
        category: "service",
        source: "actions",
        actor: "human",
        severity: "info",
        title: "notify — ok",
        lifecycle: "completed",
        result: "success",
        dedupeKey: "notify",
        session: "alice",
      }),
      expect.objectContaining({
        id: "actions:4",
        ts: "2026-08-01T01:20:00.000Z",
        severity: "error",
        title: "deploy — denied",
        lifecycle: "failed",
        result: "failure",
      }),
    ]);
    expect((events.at(0) as { project?: string }).project).toBeUndefined();
    expect(events.at(0)).not.toHaveProperty("host");
    expect(events.at(0)).not.toHaveProperty("runtime");
  });

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

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