package v1

import (
	"context"
	"strconv"

	"github.com/pingcap-inc/pchub/internal/pkg/code"
	"github.com/pingcap-inc/pchub/pkg/errors"
	"github.com/pingcap-inc/pchub/pkg/log"
)

type ListParam struct {
	Offset int `json:"offset"`
	Limit  int `json:"limit"`
}

func NewListParam() *ListParam {
	return &ListParam{
		Limit: 10,
	}
}

func (l *ListParam) Parse(ctx context.Context, params map[string]string) (*ListParam, error) {
	if params["psize"] != "" {
		limit, err := strconv.Atoi(params["psize"])
		if err != nil {
			log.L(ctx).Error("Fail to parse psize into int64, err: " + err.Error())

			return nil, errors.WithCode(code.ErrValidation, "psize must be a number")
		}
		l.Limit = limit
	}
	if params["page"] != "" {
		page, err := strconv.Atoi(params["page"])
		if err != nil {
			log.L(ctx).Error("Fail to parse page into int64, err: " + err.Error())

			return nil, errors.WithCode(code.ErrValidation, "page must be a number")
		}
		l.Offset = (page - 1) * l.Limit
	}

	return l, nil
}

type Pagination struct {
	Total int64 `json:"total"`
	Page  int   `json:"page"`
	PSize int   `json:"psize"`
}
