package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

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

	"github.com/go-pg/pg/v10/orm"
	"github.com/gorilla/schema"
	"github.com/pkg/errors"
)

// @deprecated
// HandleSubscriptionDelete godoc
// @Summary Delete subscription
// @Description Delete subscription data. Requires delete permissions
// @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 id"
// @Param name query string false "Subscription type name"
// @Param vin query string false "Subscription vin"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /subscription [delete]
func HandleSubscriptionDelete(w http.ResponseWriter, r *http.Request) {
	subscriptionDelete.Handle(w, r)
}

var subscriptionDelete = controllers.NewDelete(&subscriptionDeleteHelper{})

type subscriptionDeleteHelper struct {
	controllers.HandleDelete
}

func (h *subscriptionDeleteHelper) ParseDeleteQueryParams(r *http.Request) interface{} {
	req := queries.SubscriptionDeleteRequest{}
	decoder := schema.NewDecoder()

	decoder.SetAliasTag("json")
	decoder.Decode(&req, r.URL.Query())

	return &req
}

func (h *subscriptionDeleteHelper) ValidatePK(model interface{}) error {
	req, ok := model.(*queries.SubscriptionDeleteRequest)
	if !ok {
		return errors.New("invalid request")
	}

	if req.ID > 0 {
		return nil
	}

	err := validator.ValidateStruct(req)
	if err != nil {
		return errors.New("primary key required")
	}

	return nil
}

func (h *subscriptionDeleteHelper) QueryDelete(model interface{}) (orm.Result, error) {
	return services.GetDB().GetSubscriptions().Delete(model.(*queries.SubscriptionDeleteRequest))
}
