import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidListPriorityError, PriceListNotFoundError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePriceList, inactivePriceList } from "../testing/fixtures";
import { run } from "./updatePurchasePriceList";

describe("updatePurchasePriceList", () => {
  it("updates metadata on an active price list", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...basePriceList, name: "Updated List" };
    mock.enqueueResults([basePriceList], [updated]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: basePriceList.id, name: "Updated List" }, commandCtx),
    );

    expect(expectOk(result).purchasePriceList.name).toBe("Updated List");
  });

  it("updates metadata on an inactive price list", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...inactivePriceList, notes: "Corrected" };
    mock.enqueueResults([inactivePriceList], [updated]);

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

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

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

    await mock.withTx((trx) => run(trx, { id: basePriceList.id, priority: 20 }, 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);
  });

  it("returns error when updated priority is invalid", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList]);

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

    expectErr(result, InvalidListPriorityError);
  });
});
