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 { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePriceList, inactivePriceList } from "../testing/fixtures";
import { run } from "./deactivatePurchasePriceList";

describe("deactivatePurchasePriceList", () => {
  it("deactivates an active price list", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [{ ...basePriceList, status: "INACTIVE" }]);

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

    expect(value.purchasePriceList.status).toBe("INACTIVE");
  });

  it("returns success when the list is already inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactivePriceList]);

    const result = await mock.withTx((trx) => run(trx, { id: inactivePriceList.id }, commandCtx));
    const value = expectOk(result);

    expect(value.purchasePriceList).toEqual(inactivePriceList);
  });

  it("preserves historical purchase-order snapshots after deactivation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [{ ...basePriceList, status: "INACTIVE" }]);

    await mock.withTx((trx) => run(trx, { id: basePriceList.id }, commandCtx));

    expect(mock.updates[0].updateValues()).not.toHaveProperty("lines");
  });

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

    const result = await mock.withTx((trx) => run(trx, { id: "missing-list" }, commandCtx));

    expectErr(result, PriceListNotFoundError);
  });
});
