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

describe("listPeriodCloses", () => {
  it("returns all period closes for a company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([basePeriodClose, inProgressPeriodClose]);

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

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

  it("returns period closes filtered by fiscal year", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([basePeriodClose]);

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

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

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

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

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

  it("returns empty list when no period closes 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);
    }
  });
});
