package queries

import (
	"fmt"
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/gorilla/schema"
	"github.com/pkg/errors"
)

type PageQueryOptions struct {
	Order  string   `json:"order" validate:"max=512,sqlorder"` // Order only allows one field to be ordered, allows ASC and DESC as well. Leave empty to not apply order
	Limit  int      `json:"limit" validate:"gte=0,lte=100"`
	Offset int      `json:"offset" validate:"gte=0"`
	Ignore []string `json:"ignore" validate:"dive"`
}

var PageQueryOptionsLimitMaximum = 100

func (p *PageQueryOptions) String() string {
	return fmt.Sprintf("PageQueryOptions<%s %d %d>", p.Order, p.Limit, p.Offset)
}

// ParsePageQuery parses PageQueryOptions from http request
func ParsePageQuery(r *http.Request) (*PageQueryOptions, error) {
	decoder := schema.NewDecoder()
	options := PageQueryOptions{}

	decoder.SetAliasTag("json")
	decoder.Decode(&options, r.URL.Query())
	err := validator.ValidateStruct(options)
	if err == nil && options.Limit == 0 {
		options.Limit = PageQueryOptionsLimitMaximum
	}

	return &options, errors.WithStack(err)
}
