import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseJournalEntry, postedJournalEntry } from "../testing/fixtures";
import { run } from "./listJournalEntries";

describe("listJournalEntries", () => {
  it("returns all journal entries for a company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseJournalEntry, postedJournalEntry]);

    const result = await run(db, { companyId: "company-1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseJournalEntry, postedJournalEntry]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("returns journal entries filtered by accounting period", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseJournalEntry]);

    const result = await run(db, {
      companyId: "company-1",
      accountingPeriodId: "period-1",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseJournalEntry]);
    }
  });

  it("returns journal entries filtered by journal type", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseJournalEntry]);

    const result = await run(db, {
      companyId: "company-1",
      journalType: "MISCELLANEOUS",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseJournalEntry]);
    }
  });

  it("returns journal entries filtered by status", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([postedJournalEntry]);

    const result = await run(db, { companyId: "company-1", status: "POSTED" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([postedJournalEntry]);
    }
  });

  it("returns journal entries filtered by date range", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseJournalEntry]);

    const result = await run(db, {
      companyId: "company-1",
      startDate: new Date("2024-01-01"),
      endDate: new Date("2024-01-31"),
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseJournalEntry]);
    }
  });

  it("returns empty list when no journal entries match", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { companyId: "nonexistent" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
      expect(result.value.hasNextPage).toBe(false);
    }
  });
});
