import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ImmutableOwnerChangeError,
  InvalidListPriorityError,
  PriceListNotFoundError,
} from "../lib/errors.generated";
import { basePriceList, inactivePriceList } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updatePurchasePriceList";

describe("updatePurchasePriceList", () => {
  it("updates metadata on an active price list", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePriceList, name: "Updated List" };
    spies.select.mockReturnValueOnce(basePriceList);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const updated = { ...inactivePriceList, notes: "Corrected" };
    spies.select.mockReturnValueOnce(inactivePriceList);
    spies.update.mockReturnValueOnce(updated);

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

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

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

    await run(db, { id: basePriceList.id, priority: 20 }, commandCtx);

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

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

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

    expectErr(result, PriceListNotFoundError);
  });

  it("returns error when supplier or company ownership is changed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceList);

    const result = await run(db, { id: basePriceList.id, supplierId: "supplier-2" }, commandCtx);

    expectErr(result, ImmutableOwnerChangeError);
  });

  it("returns error when updated priority is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceList);

    const result = await run(db, { id: basePriceList.id, priority: -1 }, commandCtx);

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