import { describe, expect, test } from "bun:test";
import { readHookFiresSource } from "./hookFires";

describe("readHookFiresSource", () => {
  test("maps each JSONL record to an event carrying module, event and action", () => {
    const fixture = [
      JSON.stringify({ ts: "2026-08-15T01:00:00.000Z", event: "PreToolUse", module: "curl-timeout-gate", action: "act" }),
      JSON.stringify({ ts: "2026-08-15T01:05:00.000Z", event: "PreToolUse", module: "deny-gate", action: "deny" }),
    ].join("\n");

    const { coverage, events } = readHookFiresSource({
      path: "/tmp/hook-fires.jsonl",
      existsSyncImpl: () => true,
      readFileImpl: () => fixture,
    });

    expect(coverage).toEqual({
      id: "hook-fires",
      label: "hook fires",
      category: "guard",
      path: "/tmp/hook-fires.jsonl",
      status: "ok",
      records: 2,
      totalRecords: 2,
      skipped: 0,
      earliest: "2026-08-15T01:00:00.000Z",
      latest: "2026-08-15T01:05:00.000Z",
    });

    expect(events).toHaveLength(2);
    expect(events[0]).toMatchObject({
      id: "hook-fires:1",
      category: "guard",
      source: "hook-fires",
      actor: "system",
      severity: "info",
      title: "act (curl-timeout-gate) PreToolUse",
      dedupeKey: "curl-timeout-gate:PreToolUse:act:2026-08-15T01:00:00.000Z",
    });
    expect(events[1]).toMatchObject({ severity: "notice" });
    expect(events[1]?.detail).toMatchObject({ event: "PreToolUse", module: "deny-gate", action: "deny" });
  });

  test("reports absent when the log has never been written", () => {
    const { coverage, events } = readHookFiresSource({
      path: "/nowhere/hook-fires.jsonl",
      existsSyncImpl: () => false,
    });
    expect(coverage.status).toBe("absent");
    expect(events).toEqual([]);
  });

  test("skips corrupt lines without losing the sound ones", () => {
    const { coverage, events } = readHookFiresSource({
      path: "/tmp/hook-fires.jsonl",
      existsSyncImpl: () => true,
      readFileImpl: () => [
        "{ not json",
        JSON.stringify({ event: "PreToolUse", module: "x" }),
        JSON.stringify({ ts: "not-a-date", event: "PreToolUse", module: "x", action: "act" }),
        JSON.stringify({ ts: "2026-08-15T01:00:00.000Z", event: "Stop", module: "session-summary", action: "advise" }),
      ].join("\n"),
    });
    expect(coverage.skipped).toBe(3);
    expect(events).toHaveLength(1);
    expect(events[0]?.title).toContain("session-summary");
  });
});
