import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchaseBillLifecycle } from "../db/purchaseBill.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseBillNotCancellableError,
  PurchaseBillNotFoundError,
} from "../lib/errors.generated";

export interface CancelPurchaseBillInput {
  id: string;
}

export async function run(db: Transaction, input: CancelPurchaseBillInput, ctx: CommandContext) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "PurchaseBill",
    statusField: "status",
    id: input.id,
    transition: "cancel",
    lifecycle: purchaseBillLifecycle,
    errors: {
      notFound: PurchaseBillNotFoundError,
      invalidTransition: PurchaseBillNotCancellableError,
    },
  });
  if (!result.ok) return result;
  return ok({ purchaseBill: result.value });
}
