import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { PriceListNotFoundError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { basePriceList, basePriceRule, draftPriceRule } from "../testing/fixtures";
import { run } from "./listSalesPriceRulesByPriceList";

describe("listSalesPriceRulesByPriceList", () => {
  it("lists rules under a sales price list", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [basePriceRule, draftPriceRule]);

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

    expect(items).toHaveLength(2);
    expect(mock.selects[1].parameters).toContain(basePriceList.id);
    expect(mock.selects[1].sql).toMatch(/"salesPriceListId"/);
    expect(mock.selects[1].sql).toMatch(/order by .*"priority" desc/i);
  });

  it("filters rules by lifecycle status when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [basePriceRule]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[1].parameters).toContain("ACTIVE");
    expect(mock.selects[1].sql).toMatch(/"status"/);
  });

  it("throws when price list is not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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