import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { EmptyResultError } from "../lib/errors.generated";
import { baseAccountingPeriod, closedPeriod } from "../testing/fixtures";
import { run } from "./listAccountingPeriods";

describe("listAccountingPeriods", () => {
  it("returns error when neither companyId nor fiscalYearId is provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, {});

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(EmptyResultError);
    }
  });

  it("returns all accounting periods for a company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAccountingPeriod, closedPeriod]);

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

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

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

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

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

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

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

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

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

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

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

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