import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { PriceListNotFoundError } from "../lib/errors.generated";
import { basePriceList, basePriceRule, draftPriceRule } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSalesPriceRulesByPriceList";

describe("listSalesPriceRulesByPriceList", () => {
  it("lists rules under a sales price list", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePriceList);
    spies.select.mockReturnValueOnce([basePriceRule, draftPriceRule]);

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

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

  it("filters rules by lifecycle status when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePriceList);
    spies.select.mockReturnValueOnce([basePriceRule]);

    const result = await run(db, { salesPriceListId: basePriceList.id, status: "ACTIVE" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

  it("throws when price list is not found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { salesPriceListId: "nonexistent-id" });
    expectErr(result as never, PriceListNotFoundError);
  });
});
