package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

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

// HandleFleetGetList godoc
// @Summary Get list of fleets
// @Description Get list of fleets
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param tags query string false "Tags associated with fleet"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult{data=[]mongo.Fleet}
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleets [get]
func HandleFleetGetList(w http.ResponseWriter, r *http.Request) {
	fleetGetList.Handle(w, r)
}

var fleetGetList = controllers.NewMongoGetList(&fleetGetListHelper{})
var fleetListSort = map[string]string{
	"canbus_": "canbus.",
}

type fleetGetListHelper struct {
	fleetHelper
}

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

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

	filter.SetSearchQuery(r.URL.Query().Get("search"))
}

func (h *fleetGetListHelper) ValidateStruct(model interface{}) error { return nil }

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

	if options != nil {
		options.Order = mongo.AdaptOrder(options.Order, fleetListSort)
	}

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

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

	return client.GetFleets().GetFleetCount(filter.(*mongo.Fleet))
}
