package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
	"github.com/fiskerinc/cloud-services/pkg/validator"
)

// HandleFleetAdd godoc
// @Summary Add a fleet
// @Description Add a fleet
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param config body FleetRequest true "Fleet data"
// @Success 200 {object} FleetRequest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleet [post]
func HandleFleetAdd(w http.ResponseWriter, r *http.Request) {
	fleetCreate.Handle(w, r)
}

var fleetCreate = controllers.NewMongoCreate(&fleetCreateHelper{})

type fleetCreateHelper struct {
	fleetHelper
}

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

	fleet, ok := model.(*mongo.Fleet)
	if ok {
		if fleet.CANBus.DTCEnabled == nil {
			fleet.CANBus.DTCEnabled = elptr.ElPtr(false)
		}
	}

	return client.GetFleets().AddFleet(fleet)
}

type FleetRequest struct {
	Name        string          `json:"name"`
	LogLevel    common.LogLevel `json:"log_level" bson:"log_level"`
	CANBus      common.CANBus   `json:"canbus" bson:"canbus"`
	IDPSEnabled bool            `json:"idps_enabled" bson:"idps_enabled"`
}

type fleetHelper struct{}

func (h *fleetHelper) NewModel() interface{} {
	return &mongo.Fleet{}
}

func (h *fleetHelper) HasPK(filter interface{}) bool {
	return filter.(*mongo.Fleet).Name != ""
}

func (h *fleetHelper) ValidatePK(model interface{}) error {
	result := model.(*mongo.Fleet)

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

	return nil
}
