import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseFiscalYear, baseFiscalYear2 } from "../testing/fixtures";
import { run } from "./listFiscalYears";

describe("listFiscalYears", () => {
  it("returns all fiscal years for a company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFiscalYear, baseFiscalYear2]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseFiscalYear, baseFiscalYear2]);
      expect(result.value.hasNextPage).toBe(false);
    }
    expect(mock.selects).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("company-1");
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"startDate" asc/i);
  });

  it("returns fiscal years filtered by startDate", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFiscalYear2]);

    const result = await run(mock.db, {
      companyId: "company-1",
      startDate: new Date("2025-01-01"),
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseFiscalYear2]);
    }
    expect(mock.selects[0].sql).toMatch(/"endDate"/);
  });

  it("returns fiscal years filtered by endDate", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseFiscalYear]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([baseFiscalYear]);
    }
    expect(mock.selects[0].sql).toMatch(/"startDate"/);
  });

  it("returns empty list when no fiscal years match", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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