package handlers

import (
	"net/http"
	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/gorilla/schema"
)

// HandleAPITokensGetList godoc
// @Summary List API tokens
// @Description List API tokens. Requires API token permission
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param token query string false "API token"
// @Param role query string false "Role"
// @Param description query string false "Description"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult{data=[]common.APIToken}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /apitokens [get]
func HandleAPITokensGetList(w http.ResponseWriter, r *http.Request) {
	apiTokensGetList.Handle(w, r)
}

var apiTokensGetList = controllers.NewGetList(&apiTokensGetListHelper{})

type apiTokensGetListHelper struct {
	APITokensHelper
}

func (h *apiTokensGetListHelper) ParseGetListQueryParams(r *http.Request) interface{} {
	schema := schema.NewDecoder()
	filter := common.APIToken{}

	schema.SetAliasTag("json")
	schema.Decode(&filter, r.URL.Query())

	return &filter
}

func (h *apiTokensGetListHelper) QueryCount(filter interface{}) (int, error) {
	return services.GetDB().GetAPITokens().Count(filter.(*common.APIToken))
}

func (h *apiTokensGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	return services.GetDB().GetAPITokens().Select(filter.(*common.APIToken), options)
}

type APITokensHelper struct {
	controllers.HelperBase
}

func (h *APITokensHelper) NewModel() interface{} {
	return &common.APIToken{}
}

func (h *APITokensHelper) HasPK(filter interface{}) bool {
	result := filter.(*common.APIToken)
	return result.Token != ""
}

func (h *APITokensHelper) ValidatePK(model interface{}) error {
	result := model.(*common.APIToken)

	err := validator.ValidateField(result.Token, "required")
	if err != nil {
		return controllers.ErrorPKRequired
	}

	return nil
}
