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

describe("listTrialBalances", () => {
  it("returns all trial balances for a company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseTrialBalance]);

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

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

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

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

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

  it("returns trial balances filtered by variant", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseTrialBalance]);

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

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

  it("returns trial balances filtered by fiscal year via subquery", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseTrialBalance]);

    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([baseTrialBalance]);
    }
  });

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