package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/julienschmidt/httprouter"
)

// HandleVehicleFilterDelete godoc
// @Summary Delete filter from vehicle
// @Description Delete filter from vehicle
// @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 id path string true "CAN ID"
// @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 /vehicle/{vin}/filter/{id} [delete]
func HandleVehicleFilterDelete(w http.ResponseWriter, r *http.Request) {
	vehicleFilterDelete.Handle(w, r)
}

var vehicleFilterDelete = controllers.NewMongoDelete(&vehicleFilterDeleteHelper{})

type vehicleFilterDeleteHelper struct {
	vehicleFiltersHelper
}

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

	params := httprouter.ParamsFromContext(r.Context())
	req.VIN = params.ByName("vin")
	req.CANID = params.ByName("id")

	return req
}

func (h *vehicleFilterDeleteHelper) ValidateFields(model interface{}) error {
	p := model.(*VehicleFilterParams)
	if p.VIN == "" || p.CANID == "" {
		return ErrInvalidURLParams
	}
	return nil
}

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

	if err = client.GetVehicles().DeleteFilterForVehicle(filter.(*VehicleFilterParams).VIN, filter.(*VehicleFilterParams).CANID); err != nil {
		return err
	}

	return ResetVehiclesConfigCache([]string{filter.(*VehicleFilterParams).VIN})
}
