import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseJournalEntry, baseJournalLine, baseJournalLine2 } from "../testing/fixtures";
import { run } from "./getJournalEntry";

describe("getJournalEntry", () => {
  it("returns journal entry with journal lines when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseJournalEntry], [baseJournalLine, baseJournalLine2]);

    const result = await run(mock.db, { id: baseJournalEntry.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.journalEntry).toEqual(baseJournalEntry);
      expect(result.value.journalLines).toEqual([baseJournalLine, baseJournalLine2]);
    }
    expect(mock.selects).toHaveLength(2);
    expect(mock.selects[0].parameters).toContain(baseJournalEntry.id);
    expect(mock.selects[0].sql).toMatch(/"id"/);
    expect(mock.selects[1].parameters).toContain(baseJournalEntry.id);
    expect(mock.selects[1].sql).toMatch(/"journalEntryId"/);
  });

  it("returns null with empty journal lines when not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.journalEntry).toBeNull();
      expect(result.value.journalLines).toEqual([]);
    }
    expect(mock.selects).toHaveLength(1);
  });
});
