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

describe("listCostLayers", () => {
  it("lists cost layers by item", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

    const result = await run(db, { itemId: "item-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("lists cost layers by valuation policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

    const result = await run(db, { valuationPolicyId: "policy-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("lists cost layers by both item and valuation policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

    const result = await run(db, { itemId: "item-1", valuationPolicyId: "policy-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("returns results in oldest-first order", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

    const result = await run(db, { itemId: "item-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("returns empty list when no matches", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { itemId: "non-existent" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(0);
  });
});
