import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchaseRequisitionLifecycle } from "../db/purchaseRequisition.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseRequisitionNotCancellableError,
  PurchaseRequisitionNotFoundError,
} from "../lib/errors.generated";

export interface CancelPurchaseRequisitionInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: CancelPurchaseRequisitionInput,
  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));
  }
  const nextStatus = purchaseRequisitionLifecycle.tryTransition(requisition.status, "cancel");
  if (!nextStatus) {
    return err(new PurchaseRequisitionNotCancellableError(input.id));
  }

  const cancelled = await db
    .updateTable("PurchaseRequisition")
    .set({ status: nextStatus })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseRequisition: cancelled });
}
