import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { purchaseOrderLifecycle } from "../db/purchaseOrder.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseOrderNotFoundError,
  PurchaseOrderNotSubmittedError,
  RejectionReasonRequiredError,
} from "../lib/errors.generated";

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

export async function run(db: Transaction, input: RejectPurchaseOrderInput, ctx: CommandContext) {
  void ctx;
  const purchaseOrder = await db
    .selectFrom("PurchaseOrder")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();
  if (!purchaseOrder) {
    return err(new PurchaseOrderNotFoundError(input.id));
  }
  const nextOrderStatus = purchaseOrderLifecycle.tryTransition(purchaseOrder.orderStatus, "reject");
  if (!nextOrderStatus) {
    return err(new PurchaseOrderNotSubmittedError(input.id));
  }
  if (!input.reason.trim()) {
    return err(new RejectionReasonRequiredError(input.id));
  }

  const rejected = await db
    .updateTable("PurchaseOrder")
    .set({
      orderStatus: nextOrderStatus,
      rejectionReason: input.reason,
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseOrder: rejected });
}
