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

export interface CancelPurchaseChangeOrderInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: CancelPurchaseChangeOrderInput,
  ctx: CommandContext,
) {
  void ctx;
  const changeOrder = await db
    .selectFrom("PurchaseChangeOrder")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!changeOrder) {
    return err(new CoNotFoundError(input.id));
  }
  if (changeOrder.changeOrderStatus !== "DRAFT") {
    return err(new CoNotDraftError(input.id));
  }

  const cancelled = await db
    .updateTable("PurchaseChangeOrder")
    .set({ changeOrderStatus: "CANCELLED", updatedAt: new Date() })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ changeOrder: cancelled });
}
