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

export interface RejectPurchaseChangeOrderInput {
  id: string;
  rejectionReason: string;
}

export async function run(
  db: Transaction,
  input: RejectPurchaseChangeOrderInput,
  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 !== "SUBMITTED") {
    return err(new CoNotSubmittedError(input.id));
  }

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

  return ok({ changeOrder: rejected });
}
