import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  CurrencyNotFoundError,
  DuplicateRulePrecedenceError,
  InvalidEffectiveRangeError,
  InvalidMinimumQuantityError,
  InvalidUnitPriceError,
  ItemNotActiveError,
  ItemNotFoundError,
  PriceRuleNotFoundError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseCurrency,
  baseItem,
  basePriceRule,
  baseUnit,
  inactivePriceRule,
  inactiveItem,
} from "../testing/fixtures";
import { mockItemQueries, mockPrimitivesQueries } from "../testing/moduleMocks";
import { run } from "./updatePurchasePriceRule";

const itemQ = mockItemQueries({ item: baseItem });
const primQ = mockPrimitivesQueries({ currency: baseCurrency, unit: baseUnit });

describe("updatePurchasePriceRule", () => {
  it("updates price and quantity break on an active rule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...basePriceRule, unitPrice: "95", minimumQuantity: "5" };
    mock.enqueueResults([basePriceRule], [], [updated]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: basePriceRule.id, unitPrice: "95", minimumQuantity: "5" },
        commandCtx,
        itemQ,
        primQ,
      ),
    );

    expect(expectOk(result).purchasePriceRule.unitPrice).toBe("95");
  });

  it("updates an inactive rule without reactivating it", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...inactivePriceRule, notes: "Corrected" };
    mock.enqueueResults([inactivePriceRule], [], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: inactivePriceRule.id, notes: "Corrected" }, commandCtx, itemQ, primQ),
    );

    expect(expectOk(result).purchasePriceRule.status).toBe("INACTIVE");
  });

  it("preserves historical purchase-order snapshots after update", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule], [], [basePriceRule]);

    await mock.withTx((trx) =>
      run(trx, { id: basePriceRule.id, unitPrice: "99" }, commandCtx, itemQ, primQ),
    );

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

  it("returns error when rule does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    expectErr(
      await mock.withTx((trx) => run(trx, { id: "missing-rule" }, commandCtx, itemQ, primQ)),
      PriceRuleNotFoundError,
    );
  });

  it("returns error when updated references are invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule]);
    expectErr(
      await mock.withTx((trx) =>
        run(
          trx,
          { id: basePriceRule.id, currencyId: "missing-currency" },
          commandCtx,
          itemQ,
          mockPrimitivesQueries({ unit: baseUnit }),
        ),
      ),
      CurrencyNotFoundError,
    );
  });

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

    expectErr(
      await mock.withTx((trx) =>
        run(
          trx,
          { id: basePriceRule.id, itemId: "missing-item" },
          commandCtx,
          mockItemQueries(),
          primQ,
        ),
      ),
      ItemNotFoundError,
    );
  });

  it("returns error when the updated item is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule]);

    expectErr(
      await mock.withTx((trx) =>
        run(
          trx,
          { id: basePriceRule.id, itemId: inactiveItem.id },
          commandCtx,
          mockItemQueries({ item: inactiveItem }),
          primQ,
        ),
      ),
      ItemNotActiveError,
    );
  });

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

    expectErr(
      await mock.withTx((trx) =>
        run(
          trx,
          { id: basePriceRule.id, unitId: "missing-unit" },
          commandCtx,
          itemQ,
          mockPrimitivesQueries({ currency: baseCurrency }),
        ),
      ),
      UnitNotFoundError,
    );
  });

  it("returns error when the updated unit price is not positive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule]);

    expectErr(
      await mock.withTx((trx) =>
        run(trx, { id: basePriceRule.id, unitPrice: "0" }, commandCtx, itemQ, primQ),
      ),
      InvalidUnitPriceError,
    );
  });

  it("returns error when the updated minimum quantity is negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule]);

    expectErr(
      await mock.withTx((trx) =>
        run(trx, { id: basePriceRule.id, minimumQuantity: "-1" }, commandCtx, itemQ, primQ),
      ),
      InvalidMinimumQuantityError,
    );
  });

  it("returns error when the updated effective range is inverted", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule]);

    expectErr(
      await mock.withTx((trx) =>
        run(
          trx,
          {
            id: basePriceRule.id,
            effectiveFrom: new Date("2024-02-01T00:00:00.000Z"),
            effectiveTo: new Date("2024-01-01T00:00:00.000Z"),
          },
          commandCtx,
          itemQ,
          primQ,
        ),
      ),
      InvalidEffectiveRangeError,
    );
  });

  it("returns error when updated precedence duplicates another rule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceRule], [{ id: "other-rule" }]);
    expectErr(
      await mock.withTx((trx) => run(trx, { id: basePriceRule.id }, commandCtx, itemQ, primQ)),
      DuplicateRulePrecedenceError,
    );
  });
});
