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
// HandleSubscriptionConfigsGetList 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 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 /subscriptionconfigs [get]
func HandleSubscriptionConfigsGetList(w http.ResponseWriter, r *http.Request) {
	subscriptionConfigsGetList.Handle(w, r)
}

var subscriptionConfigsGetList = controllers.NewGetList(&subscriptionConfigsGetListHelper{})

type subscriptionConfigsGetListHelper struct {
	SubscriptionConfigsHelper
}

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

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

	return &filter
}

func (h *subscriptionConfigsGetListHelper) QueryCount(filter interface{}) (int, error) {
	return services.GetDB().GetSubConfigurations().Count(filter.(*common.SubscriptionConfiguration))
}

func (h *subscriptionConfigsGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	return services.GetDB().GetSubConfigurations().Select(filter.(*common.SubscriptionConfiguration), options)
}

type SubscriptionConfigsHelper struct {
	controllers.HelperBase
}

func (h *SubscriptionConfigsHelper) NewModel() interface{} {
	return &common.SubscriptionConfiguration{}
}

func (h *SubscriptionConfigsHelper) HasPK(filter interface{}) bool {
	result := filter.(*common.SubscriptionConfiguration)
	return result.SubscriptionFeatureID != uuid.Nil && result.ECU != ""
}

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

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

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

	return nil
}
