package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
)

// HandleFleetFilterGetList godoc
// @Summary Get filters for fleet
// @Description Get filters for fleet
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param name path string true "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 /fleet/{name}/filters [get]
func HandleFleetFilterGetList(w http.ResponseWriter, r *http.Request) {
	fleetFilterGetList.Handle(w, r)
}

var fleetFilterGetList = controllers.NewMongoGetList(&fleetFilterGetListHelper{})

type fleetFilterGetListHelper struct{}

func (h *fleetFilterGetListHelper) NewModel() interface{} {
	return &mongo.Fleet{}
}

func (h *fleetFilterGetListHelper) ParseGetListURLParams(r *http.Request, model interface{}) {
	filter := model.(*mongo.Fleet)

	params := httprouter.ParamsFromContext(r.Context())
	filter.Name = params.ByName("name")
}

func (h *fleetFilterGetListHelper) ValidateStruct(model interface{}) error {
	result := model.(*mongo.Fleet)

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

	return nil
}

func (h *fleetFilterGetListHelper) ParseGetListQueryParams(r *http.Request, model interface{}) {
	// does not utilize URL queries so leave this function empty
}

func (h *fleetFilterGetListHelper) QueryCount(filter interface{}) (int64, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return 0, err
	}

	return client.GetFleets().GetFiltersForFleetCount(filter.(*mongo.Fleet).Name)
}

func (h *fleetFilterGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}

	return client.GetFleets().GetFiltersForFleet(filter.(*mongo.Fleet).Name, options)
}
