import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { stockReservationLifecycle } from "../db/stockReservation.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  StockReservationNotFoundError,
  StockReservationNotOpenError,
} from "../lib/errors.generated";

export interface CloseStockReservationInput {
  id: string;
}

export async function run(
  db: Transaction,
  input: CloseStockReservationInput,
  _ctx: CommandContext,
) {
  const reservation = await db
    .selectFrom("StockReservation")
    .selectAll()
    .where("id", "=", input.id)
    .forUpdate()
    .executeTakeFirst();

  if (!reservation) {
    return err(new StockReservationNotFoundError(input.id));
  }

  const nextStatus = stockReservationLifecycle.tryTransition(reservation.status, "close");
  if (!nextStatus) {
    return err(new StockReservationNotOpenError(reservation.id));
  }

  const stockReservation = await db
    .updateTable("StockReservation")
    .set({ status: nextStatus })
    .where("id", "=", reservation.id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ stockReservation });
}
