package echohelpers

import (
	"strconv"

	"github.com/labstack/echo/v4"
)

// DefaultQuery returns query param with default if not present
func DefaultQuery(c echo.Context, key, defaultValue string) string {
	val := c.QueryParam(key)
	if val == "" {
		return defaultValue
	}
	return val
}

// ParseUintParam parses a path parameter as uint
func ParseUintParam(c echo.Context, name string) (uint, error) {
	val, err := strconv.ParseUint(c.Param(name), 10, 32)
	if err != nil {
		return 0, err
	}
	return uint(val), nil
}

// ParseIntParam parses a path parameter as int
func ParseIntParam(c echo.Context, name string) (int, error) {
	val, err := strconv.Atoi(c.Param(name))
	if err != nil {
		return 0, err
	}
	return val, nil
}

// BindAndValidate binds and validates the request body
func BindAndValidate(c echo.Context, req interface{}) error {
	if err := c.Bind(req); err != nil {
		return err
	}
	if err := c.Validate(req); err != nil {
		return err
	}
	return nil
}
