import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { PriceRuleNotFoundError } from "../lib/errors.generated";
import { basePriceRule, inactivePriceRule } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deactivatePurchasePriceRule";

describe("deactivatePurchasePriceRule", () => {
  it("deactivates an active price rule", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceRule);
    spies.update.mockReturnValueOnce({ ...basePriceRule, status: "INACTIVE" });

    const result = await run(db, { id: basePriceRule.id }, commandCtx);
    const value = expectOk<{ purchasePriceRule: typeof basePriceRule }>(result);

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

  it("returns success when the rule is already inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePriceRule);

    const result = await run(db, { id: inactivePriceRule.id }, commandCtx);
    const value = expectOk<{ purchasePriceRule: typeof inactivePriceRule }>(result);

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

  it("preserves historical purchase-order snapshots after deactivation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceRule);
    spies.update.mockReturnValueOnce({ ...basePriceRule, status: "INACTIVE" });

    await run(db, { id: basePriceRule.id }, commandCtx);

    const firstSetCall = spies.set.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(firstSetCall).not.toHaveProperty("matchedPriceRuleId");
  });

  it("returns error when rule does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing-rule" }, commandCtx);

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