import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CurrencyNotFoundError,
  DuplicateRulePrecedenceError,
  InvalidEffectiveRangeError,
  InvalidMinimumQuantityError,
  InvalidUnitPriceError,
  ItemNotActiveError,
  ItemNotFoundError,
  PriceRuleNotFoundError,
  UnitNotFoundError,
} from "../lib/errors.generated";
import {
  baseCurrency,
  baseItem,
  basePriceRule,
  baseUnit,
  inactivePriceRule,
  inactiveItem,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updatePurchasePriceRule";

describe("updatePurchasePriceRule", () => {
  it("updates price and quantity break on an active rule", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePriceRule, unitPrice: 95, minimumQuantity: 5 };
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit)
      .mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      { id: basePriceRule.id, unitPrice: 95, minimumQuantity: 5 },
      commandCtx,
    );

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

  it("updates an inactive rule without reactivating it", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...inactivePriceRule, notes: "Corrected" };
    spies.select
      .mockReturnValueOnce(inactivePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit)
      .mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(db, { id: inactivePriceRule.id, notes: "Corrected" }, commandCtx);

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

  it("preserves historical purchase-order snapshots after update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit)
      .mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce(basePriceRule);

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

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

  it("returns error when rule does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    expectErr(await run(db, { id: "missing-rule" }, commandCtx), PriceRuleNotFoundError);
  });

  it("returns error when updated references are invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(undefined);
    expectErr(
      await run(db, { id: basePriceRule.id, currencyId: "missing-currency" }, commandCtx),
      CurrencyNotFoundError,
    );
  });

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

    expectErr(
      await run(db, { id: basePriceRule.id, itemId: "missing-item" }, commandCtx),
      ItemNotFoundError,
    );
  });

  it("returns error when the updated item is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceRule).mockReturnValueOnce(inactiveItem);

    expectErr(
      await run(db, { id: basePriceRule.id, itemId: inactiveItem.id }, commandCtx),
      ItemNotActiveError,
    );
  });

  it("returns error when the updated unit does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(undefined);

    expectErr(
      await run(db, { id: basePriceRule.id, unitId: "missing-unit" }, commandCtx),
      UnitNotFoundError,
    );
  });

  it("returns error when the updated unit price is not positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit);

    expectErr(
      await run(db, { id: basePriceRule.id, unitPrice: 0 }, commandCtx),
      InvalidUnitPriceError,
    );
  });

  it("returns error when the updated minimum quantity is negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit);

    expectErr(
      await run(db, { id: basePriceRule.id, minimumQuantity: -1 }, commandCtx),
      InvalidMinimumQuantityError,
    );
  });

  it("returns error when the updated effective range is inverted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit);

    expectErr(
      await run(
        db,
        {
          id: basePriceRule.id,
          effectiveFrom: new Date("2024-02-01T00:00:00.000Z"),
          effectiveTo: new Date("2024-01-01T00:00:00.000Z"),
        },
        commandCtx,
      ),
      InvalidEffectiveRangeError,
    );
  });

  it("returns error when updated precedence duplicates another rule", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePriceRule)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce(baseCurrency)
      .mockReturnValueOnce(baseUnit)
      .mockReturnValueOnce({ id: "other-rule" });
    expectErr(await run(db, { id: basePriceRule.id }, commandCtx), DuplicateRulePrecedenceError);
  });
});
