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/julienschmidt/httprouter"
)

// HandleVehicleFilterGetList godoc
// @Summary Get filters for car
// @Description Get filters for 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 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}/filters [get]
func HandleVehicleFilterGetList(w http.ResponseWriter, r *http.Request) {
	vehicleFilterGetList.Handle(w, r)
}

var vehicleFilterGetList = controllers.NewMongoGetList(&vehicleFilterGetListHelper{})

type vehicleFilterGetListHelper struct {
	vehicleFiltersHelper
}

func (h *vehicleFilterGetListHelper) NewModel() interface{} {
	return &VehicleFilterParams{}
}

func (h *vehicleFilterGetListHelper) ParseGetListURLParams(r *http.Request, model interface{}) {
	filter := model.(*VehicleFilterParams)

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

func (h *vehicleFilterGetListHelper) ValidateStruct(model interface{}) error {
	result := model.(*VehicleFilterParams)

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

	return nil
}

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

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

	return client.GetVehicles().GetFilterCountForVehicle(filter.(*VehicleFilterParams).VIN)
}

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

	return client.GetVehicles().GetFiltersForVehicle(filter.(*VehicleFilterParams).VIN, options)
}
