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

export interface ClosePurchaseRequisitionInput {
  id: string;
  closeReason?: string;
}

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

  const closed = await db
    .updateTable("PurchaseRequisition")
    .set({
      status: "CLOSED",
      closeReason: input.closeReason ?? null,
      updatedAt: new Date(),
    })
    .where("id", "=", input.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchaseRequisition: closed });
}
