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

export interface RejectPurchaseRequisitionInput {
  id: string;
  reason: string;
}

export async function run(
  db: Transaction,
  input: RejectPurchaseRequisitionInput,
  ctx: CommandContext,
) {
  void ctx;
  const requisition = await db
    .selectFrom("PurchaseRequisition")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!requisition) {
    return err(new PurchaseRequisitionNotFoundError(input.id));
  }
  if (requisition.status !== "SUBMITTED") {
    return err(new PurchaseRequisitionNotSubmittedError(input.id));
  }
  if (!input.reason.trim()) {
    return err(new RejectionReasonRequiredError(input.id));
  }

  const updated = await db
    .updateTable("PurchaseRequisition")
    .set({
      status: "DRAFT",
      rejectionReason: input.reason,
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseRequisition: updated });
}
