import type { Transaction } from "../generated/kysely-tailordb";
import { ChannelOrderNotFoundError, InvalidChannelOrderStatusError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CancelChannelOrderInput {
  channelOrderId: string;
}

export async function run(db: Transaction, input: CancelChannelOrderInput, ctx: CommandContext) {
  void ctx;
  const channelOrder = await db
    .selectFrom("ChannelOrder")
    .selectAll()
    .where("id", "=", input.channelOrderId)
    .forUpdate()
    .executeTakeFirst();
  if (!channelOrder) {
    return err(new ChannelOrderNotFoundError(input.channelOrderId));
  }
  if (!["PENDING_CONVERSION", "EXCEPTION"].includes(channelOrder.status)) {
    return err(new InvalidChannelOrderStatusError(input.channelOrderId));
  }
  const updated = await db
    .updateTable("ChannelOrder")
    .set({ status: "CANCELLED_BY_CHANNEL", updatedAt: new Date() })
    .where("id", "=", input.channelOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ channelOrder: updated! });
}
