import { FastifyRequest, FastifyReply } from 'fastify'
import { handleError } from './errorHandler.js'

/**
 * Type for route handler functions
 */
type RouteHandler<T = any> = (request: FastifyRequest, reply: FastifyReply) => Promise<T>

/**
 * Wraps a route handler with error handling logic
 * 
 * @param handler - The original route handler function
 * @param endpoint - The endpoint identifier for tracking
 * @returns A wrapped handler with error handling
 */
export function withErrorHandling<T = any>(handler: RouteHandler<T>, endpoint: string): RouteHandler<T> {
  return async (request: FastifyRequest, reply: FastifyReply): Promise<T> => {
    try {
      return await handler(request, reply)
    } catch (error) {
      return handleError(request, reply, error, endpoint) as T
    }
  }
}

/**
 * Creates a route handler with built-in error handling
 * 
 * @param endpoint - The endpoint identifier for tracking
 * @param handlerFn - The handler function logic
 * @returns A route handler with error handling
 */
export function createHandler<T = any>(endpoint: string, handlerFn: RouteHandler<T>): RouteHandler<T> {
  return withErrorHandling(handlerFn, endpoint)
} 