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

describe("listSalesPriceLists", () => {
  it("lists sales price lists by company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList, draftPriceList]);

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

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

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

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

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

  it("throws when company scope is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await run(mock.db, { companyId: "" });
    expectErr(result as never, CompanyScopeRequiredError);
  });
});
