import { describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { readLandqSource } from "./landq";

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

describe("readLandqSource", () => {
  test("reads each repo root, honors window, and keeps stable IDs", () => {
    const fixtureA = readFileSync(FIXTURE_PATH, "utf8");
    const fixtureB = `{"ticket":"ticket-b","branch":"root-b","at":"2026-08-01T10:10:00.000Z"}\n`;

    const rootDir = mkdtempSync(join(tmpdir(), "overdeck-landq-"));
    const repoA = join(rootDir, "repo-a");
    const repoB = join(rootDir, "repo-b");
    const landqA = join(repoA, ".git", "harness", "landq", "log");
    const landqB = join(repoB, ".git", "harness", "landq", "log");

    try {
      mkdirSync(dirname(landqA), { recursive: true });
      mkdirSync(dirname(landqB), { recursive: true });
      writeFileSync(landqA, fixtureA, "utf8");
      writeFileSync(landqB, fixtureB, "utf8");

      const result = readLandqSource({
        repoRoots: [repoA, repoB],
        existsSyncImpl: (path) => path === landqA || path === landqB,
        readFileImpl: (path) => path === landqA ? fixtureA : fixtureB,
        fromMs: Date.parse("2026-08-01T10:00:00.000Z"),
        toMs: Date.parse("2026-08-01T10:20:00.000Z"),
      });

      expect(result.coverage).toEqual({
        id: "landq",
        label: "land queue",
        category: "land",
        path: `${landqA};${landqB}`,
        status: "ok",
        records: 2,
        totalRecords: 4,
        skipped: 2,
        earliest: "2026-07-31T23:00:00.000Z",
        latest: "2026-08-01T10:30:00.000Z",
      });
      expect(result.events).toHaveLength(2);
      expect(result.events).toEqual([
        expect.objectContaining({
          id: "landq:1",
          project: "repo-a",
          title: "queued main (gate deploy, depth 9)",
          session: "ticket-in-range",
          severity: "info",
        }),
        expect.objectContaining({
          id: "landq:6",
          project: "repo-b",
          title: "queued root-b",
          session: "ticket-b",
        }),
      ]);
    } finally {
      rmSync(rootDir, { recursive: true, force: true });
    }
  });

  test("reports absent if no landq roots exist", () => {
    const result = readLandqSource({
      repoRoots: [join(tmpdir(), "no-such-repo")],
      existsSyncImpl: () => false,
    });

    expect(result.events).toEqual([]);
    expect(result.coverage).toEqual({
      id: "landq",
      label: "land queue",
      category: "land",
      path: `${join(tmpdir(), "no-such-repo")}/.git/harness/landq/log`,
      status: "absent",
      records: 0,
      totalRecords: 0,
      skipped: 0,
    });
  });
});
