import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { goodsReceiptLifecycle } from "../db/goodsReceipt.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { GoodsReceiptNotDraftError, GoodsReceiptNotFoundError } from "../lib/errors.generated";

export interface CancelGoodsReceiptInput {
  id: string;
}

export async function run(db: Transaction, input: CancelGoodsReceiptInput, ctx: CommandContext) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "GoodsReceipt",
    statusField: "status",
    id: input.id,
    transition: "cancel",
    lifecycle: goodsReceiptLifecycle,
    errors: {
      notFound: GoodsReceiptNotFoundError,
      invalidTransition: GoodsReceiptNotDraftError,
    },
  });
  if (!result.ok) return result;
  return ok({ goodsReceipt: result.value });
}
