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
// HandleSubscriptionPackagesGetList godoc
// @Summary Search subscription packages
// @Description Get subscription packages filtered by id, 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 package id"
// @Param name query string false "Subscription package 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 /subscriptionpackages [get]
func HandleSubscriptionPackagesGetList(w http.ResponseWriter, r *http.Request) {
	subscriptionPackagesGetList.Handle(w, r)
}

var subscriptionPackagesGetList = controllers.NewGetList(&subscriptionPackagesGetListHelper{})

type subscriptionPackagesGetListHelper struct {
	SubscriptionPackagesHelper
}

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

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

	return &filter
}

func (h *subscriptionPackagesGetListHelper) QueryCount(filter interface{}) (int, error) {
	return services.GetDB().GetSubPackages().Count(filter.(*common.SubscriptionPackage))
}

func (h *subscriptionPackagesGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	return services.GetDB().GetSubPackages().Select(filter.(*common.SubscriptionPackage), options)
}

type SubscriptionPackagesHelper struct {
	controllers.HelperBase
}

func (h *SubscriptionPackagesHelper) NewModel() interface{} {
	return &common.SubscriptionPackage{}
}

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

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

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

	return nil
}
