package handlers

import (
	"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"
	"net/http"
	"otaupdate/controllers"
	"otaupdate/services"
)

// HandleVehicleFleetGetList godoc
// @Summary Get fleets of car
// @Description Get fleets of a car
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin path string true "VIN"
// @Param search query string true "FLEET_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 /vehicle/{vin}/fleets [get]
func HandleVehicleFleetGetList(w http.ResponseWriter, r *http.Request) {
	vehicleFleetList.Handle(w, r)
}

var vehicleFleetList = controllers.NewMongoGetList(&vehicleFleetListModelHelper{})

type vehicleFleetListModelHelper struct{}

func (v vehicleFleetListModelHelper) NewModel() interface{} {
	return &mongo.Vehicle{}
}

func (v vehicleFleetListModelHelper) ParseGetListURLParams(r *http.Request, model interface{}) {
	filter := model.(*mongo.Vehicle)

	params := httprouter.ParamsFromContext(r.Context())
	filter.VIN = params.ByName("vin")
}

func (v vehicleFleetListModelHelper) ParseGetListQueryParams(r *http.Request, model interface{}) {
	filter := model.(*mongo.Vehicle)

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

func (v vehicleFleetListModelHelper) ValidateStruct(model interface{}) error {
	result := model.(*mongo.Vehicle)

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

	return nil
}

func (v vehicleFleetListModelHelper) QueryCount(filter interface{}) (int64, error) {
	f := filter.(*mongo.Vehicle)

	client, err := services.GetMongoClient()
	if err != nil {
		return 0, err
	}

	return client.GetVehicles().GetFleetCountForVehicle(f.VIN, f.SearchQuery())
}

func (v vehicleFleetListModelHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	f := filter.(*mongo.Vehicle)

	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}

	return client.GetVehicles().GetFleetsForVehicle(f.VIN, f.SearchQuery(), options)
}
