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

export interface RejectInventoryAdjustmentInput {
  id: string;
}

/**
 * Function: rejectInventoryAdjustment
 *
 * Rejects a pending inventory adjustment, transitioning it from PENDING_APPROVAL to REJECTED status.
 */
export async function run(
  db: Transaction,
  input: RejectInventoryAdjustmentInput,
  _ctx: CommandContext,
) {
  const { id } = input;

  // 1. Fetch adjustment
  const adjustment = await db
    .selectFrom("InventoryAdjustment")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!adjustment) {
    return err(new AdjustmentNotFoundError(id));
  }

  // 2. Validate status is PENDING_APPROVAL
  if (adjustment.status !== "PENDING_APPROVAL") {
    return err(new AdjustmentNotPendingApprovalError(id));
  }

  // 3. Update status to REJECTED
  const updated = await db
    .updateTable("InventoryAdjustment")
    .set({ status: "REJECTED", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ inventoryAdjustment: updated! });
}
