package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/julienschmidt/httprouter"
)

// HandleFleetVehicleDelete godoc
// @Summary Delete vehicle from fleet
// @Description Delete vehicle from 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 vins body common.VINs true "VINs"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleet/{name}/vehicles/delete [post]
func HandleFleetVehicleDelete(w http.ResponseWriter, r *http.Request) {
	fleetVehicleDelete.Handle(w, r)
}

var fleetVehicleDelete = controllers.NewMongoDelete(&fleetVehicleDeleteHelper{})

type fleetVehicleDeleteHelper struct{}

func (h *fleetVehicleDeleteHelper) ParseDeleteURLParams(r *http.Request) interface{} {
	req := &FleetVehicleDeleteParams{}

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

	httphandlers.ParseRequest(r, &req) // Populate VINs from body

	return req
}

func (h *fleetVehicleDeleteHelper) ValidateFields(model interface{}) error {
	result := model.(*FleetVehicleDeleteParams)

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

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

	return nil
}

func (h *fleetVehicleDeleteHelper) QueryDelete(filter interface{}) error {
	client, err := services.GetMongoClient()
	if err != nil {
		return err
	}

	fleet := filter.(*FleetVehicleDeleteParams)

	err = client.GetFleets().DeleteVehiclesFromFleet(fleet.Name, fleet.VINs)
	if err != nil {
		return err
	}

	return ResetVehiclesConfigCache(fleet.VINs)
}

type FleetVehicleDeleteParams struct {
	Name string   `validate:"required,fleet"`
	VINs []string `json:"vins" validate:"required,max=1000,dive,vin"`
}
