import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CoNotDraftError, CoNotFoundError } from "../lib/errors.generated";
import { basePurchaseChangeOrder, submittedChangeOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelPurchaseChangeOrder";

describe("cancelPurchaseChangeOrder", () => {
  it("cancels a valid draft change order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...basePurchaseChangeOrder, changeOrderStatus: "CANCELLED" };
    spies.select.mockReturnValueOnce(basePurchaseChangeOrder); // selectOne PurchaseChangeOrder
    spies.update.mockReturnValueOnce(cancelled);

    const result = await run(db, { id: basePurchaseChangeOrder.id }, commandCtx);

    expect(expectOk(result).changeOrder.changeOrderStatus).toBe("CANCELLED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ changeOrderStatus: "CANCELLED" }),
    );
  });

  it("does not modify the target purchase order on cancellation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...basePurchaseChangeOrder, changeOrderStatus: "CANCELLED" };
    spies.select.mockReturnValueOnce(basePurchaseChangeOrder);
    spies.update.mockReturnValueOnce(cancelled);

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

    // Only one update call — for the change order itself
    expect(spies.update).toHaveBeenCalledTimes(1);
  });

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

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

    expectErr(result, CoNotFoundError);
  });

  it("returns error when change order is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedChangeOrder);

    const result = await run(db, { id: submittedChangeOrder.id }, commandCtx);

    expectErr(result, CoNotDraftError);
  });
});
