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/google/uuid"
	"github.com/gorilla/schema"
)

// @deprecated
// HandleSubscriptionFeaturesGet godoc
// @Summary Search subscription features
// @Description Get subscription features filtered by id or name
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id query string false "Subscription feature id"
// @Param name query string false "Subscription feature name"
// @Param description query string false "Subscription feature description"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /subscriptionfeatures [get]
func HandleSubscriptionFeaturesGet(w http.ResponseWriter, r *http.Request) {
	subscriptionFeaturesGet.Handle(w, r)
}

var subscriptionFeaturesGet = controllers.NewGetList(&subscriptionFeaturesGetListHelper{})

type subscriptionFeaturesGetListHelper struct {
	SubscriptionFeatureHelper
}

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

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

	return &filter
}

func (h *subscriptionFeaturesGetListHelper) QueryCount(filter interface{}) (int, error) {
	return services.GetDB().GetSubFeatures().Count(filter.(*common.SubscriptionFeature))
}

func (h *subscriptionFeaturesGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	return services.GetDB().GetSubFeatures().Select(filter.(*common.SubscriptionFeature), options)
}

type SubscriptionFeatureHelper struct {
	controllers.HelperBase
}

func (h *SubscriptionFeatureHelper) NewModel() interface{} {
	return &common.SubscriptionFeature{}
}

func (h *SubscriptionFeatureHelper) HasPK(filter interface{}) bool {
	result := filter.(*common.SubscriptionFeature)
	return result.ID != uuid.Nil || result.Name != ""
}

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

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

	return nil
}
