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 ApproveInventoryAdjustmentInput {
  id: string;
}

/**
 * Function: approveInventoryAdjustment
 *
 * Approves a pending inventory adjustment, transitioning it from PENDING_APPROVAL to APPROVED status.
 */
export async function run(
  db: Transaction,
  input: ApproveInventoryAdjustmentInput,
  _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 APPROVED
  const updated = await db
    .updateTable("InventoryAdjustment")
    .set({ status: "APPROVED", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

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