package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/mongo"

	"github.com/julienschmidt/httprouter"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

// HandleFleetGet godoc
// @Summary Get fleet
// @Description Get 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"
// @Success 200 {object} mongo.Fleet
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleet/{name} [get]
func HandleFleetGet(w http.ResponseWriter, r *http.Request) {
	fleetGet.Handle(w, r)
}

var fleetGet = controllers.NewMongoGetModel(&fleetGetModelHelper{})

type fleetGetModelHelper struct {
	fleetHelper
}

func (h *fleetGetModelHelper) ParseGetURLParams(r *http.Request) interface{} {
	req := &mongo.Fleet{}

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

	return req
}

func (h *fleetGetModelHelper) Query(filter interface{}) (interface{}, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}
	fleet, ok := filter.(*mongo.Fleet)
	if ok {
		if fleet.CANBus.DTCEnabled == nil {
			fleet.CANBus.DTCEnabled = elptr.ElPtr(false)
		}
	}
	return client.GetFleets().FindFleet(filter.(*mongo.Fleet))
}

type FleetFilterParams struct {
	Name string `json:"name" validate:"required,fleet"`
}
