import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseItemValuation } from "../testing/fixtures";
import { run } from "./listItemValuations";

describe("listItemValuations", () => {
  it("lists all item valuations", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation]);

    const result = await run(mock.db, {});
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseItemValuation);
  });

  it("filters by item IDs", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation]);

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

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseItemValuation);
    expect(mock.selects[0].parameters).toContain("item-1");
    expect(mock.selects[0].sql).toMatch(/"itemId"/);
  });

  it("filters by valuation policy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItemValuation]);

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

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseItemValuation);
    expect(mock.selects[0].parameters).toContain("policy-1");
    expect(mock.selects[0].sql).toMatch(/"valuationPolicyId"/);
  });

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

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

    expect(items).toHaveLength(0);
    expect(hasNextPage).toBe(false);
  });
});
