import { NextApiHandler } from 'next'
import { UserRole } from './types'
import { withAuth, AuthenticatedHandler } from './withAuth'

/**
 * Protect an API route requiring a specific role or higher
 *
 * @example
 * // Only admins can access
 * export default requireRole(handler, UserRole.ADMIN)
 *
 * // Growers and above can access
 * export default requireRole(handler, UserRole.GROWER)
 */
export function requireRole(
  handler: AuthenticatedHandler,
  role: UserRole
): NextApiHandler {
  return withAuth(handler, { requiredRole: role })
}

/**
 * Protect an API route requiring admin role
 */
export function requireAdmin(handler: AuthenticatedHandler): NextApiHandler {
  return requireRole(handler, UserRole.ADMIN)
}

/**
 * Protect an API route requiring farm manager role or higher
 */
export function requireFarmManager(handler: AuthenticatedHandler): NextApiHandler {
  return requireRole(handler, UserRole.FARM_MANAGER)
}

/**
 * Protect an API route requiring grower role or higher
 */
export function requireGrower(handler: AuthenticatedHandler): NextApiHandler {
  return requireRole(handler, UserRole.GROWER)
}

/**
 * Protect an API route requiring any authenticated user
 */
export function requireUser(handler: AuthenticatedHandler): NextApiHandler {
  return withAuth(handler)
}

// Re-export for convenience
export { withAuth, withPermission, withAnyPermission, withAllPermissions } from './withAuth'
