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

describe("activateSalesPriceList", () => {
  it("activates a draft SalesPriceList", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activated = {
      ...draftPriceList,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([draftPriceList], [activated]);

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

    expectOk(result);
  });

  it("throws when SalesPriceList is not in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList]);

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

    expectErr(result, InvalidSalespricelistStatusError);
  });

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

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

    expectErr(result, SalespricelistNotFoundError);
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, { salesPriceListId: draftPriceList.id }, commandCtx, mockOrgQueries(null)),
    );

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