import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { channelOrderLifecycle } from "../db/channelOrder.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { ChannelOrderNotFoundError, InvalidChannelOrderStatusError } from "../lib/errors.generated";

export interface CancelChannelOrderInput {
  channelOrderId: string;
}

export async function run(db: Transaction, input: CancelChannelOrderInput, ctx: CommandContext) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "ChannelOrder",
    statusField: "status",
    id: input.channelOrderId,
    transition: "cancel",
    lifecycle: channelOrderLifecycle,
    errors: {
      notFound: ChannelOrderNotFoundError,
      invalidTransition: InvalidChannelOrderStatusError,
    },
  });
  if (!result.ok) return result;
  return ok({ channelOrder: result.value });
}
