package handlers

import (
	"net/http"

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

	"otaupdate/controllers"
	"otaupdate/services"

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

	"github.com/julienschmidt/httprouter"
	"github.com/pkg/errors"
)

// HandleFleetFilterUpdate godoc
// @Summary Update a fleet filter
// @Description Update a fleet filter
// @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"
// @Param config body common.CANFilter true "Fleet filter data"
// @Success 200 {object} common.SubscriptionConfiguration
// @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} [put]
func HandleFleetFilterUpdate(w http.ResponseWriter, r *http.Request) {
	fleetFilterUpdate.Handle(w, r)
}

var fleetFilterUpdate = controllers.NewMongoUpdate(&fleetFilterUpdateHelper{})

type fleetFilterUpdateHelper struct{}

func (h *fleetFilterUpdateHelper) ParseUpdateURLParams(r *http.Request) interface{} {
	req := &FleetFilterUpdateParams{}

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

	return req
}

func (h *fleetFilterUpdateHelper) ValidateFields(model interface{}) error {
	result, ok := model.(*FleetFilterUpdateParams)
	if !ok {
		return nil
	}

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

	return nil
}

func (h *fleetFilterUpdateHelper) NewModel() interface{} {
	return &common.CANFilter{}
}

func (h *fleetFilterUpdateHelper) ParseRequestBody(r *http.Request, model interface{}) error {
	if err := httphandlers.ParseRequest(r, model); err != nil {
		return errors.WithMessage(err, "failed to parse request body")
	}

	p := model.(*common.CANFilter)

	if p.EdgeMask == nil && p.Interval == nil {
		return &validator.FieldError{
			ErrorMsg: "At least one of edge_mask or interval is required",
		}
	}

	if p.EdgeMask != nil && p.Interval != nil {
		if (*p.EdgeMask).String() == "" && *p.Interval == 0 ||
			(*p.EdgeMask).String() != "" && *p.Interval != 0 {
			return &validator.FieldError{
				ErrorMsg: "Only one of edge_mask or interval can be specified",
			}
		}
	}

	return nil
}

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

	f := filter.(*FleetFilterUpdateParams)
	if err = client.GetFleets().UpdateFilterForFleet(f.Name, f.CANID, model.(*common.CANFilter)); err != nil {
		return err
	}

	return ResetFleetVehiclesConfigCache(f.Name)
}

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