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 {
  PurchaseRequisitionNotFoundError,
  PurchaseRequisitionNotSubmittedError,
  SelfApprovalNotAllowedError,
} from "../lib/errors.generated";

export interface ApprovePurchaseRequisitionInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: ApprovePurchaseRequisitionInput,
  ctx: CommandContext,
) {
  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, "approve");
  if (!nextStatus) {
    return err(new PurchaseRequisitionNotSubmittedError(input.id));
  }
  if (ctx.actorId === requisition.requesterId) {
    return err(new SelfApprovalNotAllowedError(input.id));
  }

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

  return ok({ purchaseRequisition: updated });
}
