package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

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

// HandleFleetFilterDelete godoc
// @Summary Delete filter from fleet
// @Description Delete filter 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 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 /fleet/{name}/filter/{id} [delete]
func HandleFleetFilterDelete(w http.ResponseWriter, r *http.Request) {
	fleetFilterDelete.Handle(w, r)
}

var fleetFilterDelete = controllers.NewMongoDelete(&fleetFilterDeleteHelper{})

type fleetFilterDeleteHelper struct{}

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

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

	return req
}

func (h *fleetFilterDeleteHelper) ValidateFields(model interface{}) error {
	result := model.(*FleetFilterDeleteParams)

	err := validator.ValidateStruct(result)
	if err != nil {
		return controllers.ErrorPKRequired
	}

	return nil
}

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

	f := filter.(*FleetFilterDeleteParams)

	if err = client.GetFleets().DeleteFilterFromFleet(f.Name, f.CANID); err != nil {
		return err
	}

	return ResetFleetVehiclesConfigCache(f.Name)
}

type FleetFilterDeleteParams struct {
	Name  string `validate:"fleet"`
	CANID string `validate:"can_id"`
}
