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

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

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

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

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

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

    expect(value.purchasePriceList).toEqual(inactivePriceList);
  });

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

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

    const firstSetCall = spies.set.mock.calls[0]?.[0] as Record<string, unknown>;
    expect(firstSetCall).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);
  });
});
