import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { GoodsReceiptNotDraftError, GoodsReceiptNotFoundError } from "../lib/errors.generated";
import { baseGoodsReceipt, postedGoodsReceipt } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelGoodsReceipt";

describe("cancelGoodsReceipt", () => {
  it("cancels a draft goods receipt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    spies.update.mockReturnValueOnce({ ...baseGoodsReceipt, status: "CANCELLED" });

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

    expect(expectOk(result).goodsReceipt.status).toBe("CANCELLED");
  });

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

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

    expectErr(result, GoodsReceiptNotFoundError);
  });

  it("returns error when goods receipt is already posted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(postedGoodsReceipt);

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

    expectErr(result, GoodsReceiptNotDraftError);
  });
});
