package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

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

// HandleFleetDelete godoc
// @Summary Delete fleet
// @Description Delete 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"
// @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} [delete]
func HandleFleetDelete(w http.ResponseWriter, r *http.Request) {
	fleetDelete.Handle(w, r)
}

var fleetDelete = controllers.NewMongoDelete(&fleetDeleteHelper{})

type fleetDeleteHelper struct {
	fleetHelper
}

func (h *fleetDeleteHelper) ParseDeleteURLParams(r *http.Request) interface{} {
	var req = &mongo.Fleet{}

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

	return req
}

func (h *fleetDeleteHelper) ValidateFields(model interface{}) error {
	p := model.(*mongo.Fleet)

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

	return nil
}

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

	return client.GetFleets().DeleteFleet(model.(*mongo.Fleet))
}

type FleetDeleteRequest struct {
	Name string `validate:"required,fleet"`
}
