import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CompanyNotFoundError, IdentifierRequiredError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseCompany, basePriceList } from "../testing/fixtures";
import { mockOrgQueries } from "../testing/moduleMocks";
import { run } from "./createSalesPriceList";

describe("createSalesPriceList", () => {
  it("creates a draft price list for a valid company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = { ...basePriceList, id: "price-list-9", status: "DRAFT" as const };
    mock.enqueueResults([created]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: "Promo Prices", code: "PROMO" },
        commandCtx,
        mockOrgQueries(baseCompany),
      ),
    );

    const value = expectOk(result);
    expect(value.salesPriceList).toEqual(created);
  });

  it("throws when required SalesPriceList fields are missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { companyId: baseCompany.id, name: "" }, commandCtx, mockOrgQueries(baseCompany)),
    );

    expectErr(result, IdentifierRequiredError);
  });

  it("creates the SalesPriceList in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...basePriceList, status: "DRAFT" as const }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: basePriceList.name, priority: basePriceList.priority },
        commandCtx,
        mockOrgQueries(baseCompany),
      ),
    );

    expectOk(result);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        companyId: baseCompany.id,
        status: "DRAFT",
      }),
    );
  });

  it("throws when the company does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: basePriceList.name },
        commandCtx,
        mockOrgQueries(null),
      ),
    );

    expectErr(result, CompanyNotFoundError);
  });
});
