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

describe("getChartOfAccounts", () => {
  it("returns CoA when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseDraftCoa);

    const result = await run(db, { id: baseDraftCoa.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toEqual(baseDraftCoa);
    }
  });

  it("returns null when CoA not found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toBeNull();
    }
  });

  it("returns CoA when found by companyId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseActiveCoa);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toEqual(baseActiveCoa);
    }
  });

  it("returns null when CoA not found by companyId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toBeNull();
    }
  });

  it("returns CoA when found by companyId with status filter", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(baseActiveCoa);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toEqual(baseActiveCoa);
    }
  });

  it("returns null when no CoA matches companyId and status filter", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue(undefined);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.chartOfAccounts).toBeNull();
    }
  });
});
