package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

const maxParamLen = 255

// ValidatePathParams rejects requests with null bytes or excessively long
// path parameters. This prevents 500s from invalid UUIDs reaching the
// database layer.
func ValidatePathParams() gin.HandlerFunc {
	return func(c *gin.Context) {
		for _, p := range c.Params {
			if len(p.Value) > maxParamLen {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
					"error": "path parameter too long",
				})
				return
			}
			if strings.ContainsRune(p.Value, 0) {
				c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
					"error": "invalid character in path parameter",
				})
				return
			}
		}
		c.Next()
	}
}
