package handler

import (
	"errors"
	"strconv"
	"strings"

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

var errInvalidPositiveUint = errors.New("参数必须是正整数")

func positiveUint(raw string) (uint, error) {
	parsed, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)
	if err != nil || parsed == 0 || uint64(uint(parsed)) != parsed {
		return 0, errInvalidPositiveUint
	}
	return uint(parsed), nil
}

func positiveUintQuery(c *gin.Context, key string) (uint, error) {
	return positiveUint(c.Query(key))
}

func positiveUintParam(c *gin.Context, key string) (uint, error) {
	return positiveUint(c.Param(key))
}

func page(c *gin.Context) (int, int, error) {
	var value, size int
	if raw, exists := c.GetQuery("page"); exists && raw != "" {
		parsed, err := strconv.Atoi(raw)
		if err != nil {
			return 0, 0, err
		}
		value = parsed
	}
	if raw, exists := c.GetQuery("pageSize"); exists && raw != "" {
		parsed, err := strconv.Atoi(raw)
		if err != nil {
			return 0, 0, err
		}
		size = parsed
	}
	return value, size, nil
}

func IDsFromQuery(c *gin.Context) ([]uint, error) {
	values := c.QueryArray("IDs[]")
	if len(values) == 0 {
		return nil, errInvalidPositiveUint
	}
	ids := make([]uint, 0, len(values))
	for _, value := range values {
		id, err := positiveUint(value)
		if err != nil {
			return nil, err
		}
		ids = append(ids, id)
	}
	return ids, nil
}
