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

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

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

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

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

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

    expect(value.purchasePriceRule).toEqual(inactivePriceRule);
  });

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

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

    expectErr(result, PriceRuleNotFoundError);
  });
});
