package handlers

import (
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/pkg/errors"

	"otaupdate/controllers"
	"otaupdate/services"

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

	"github.com/julienschmidt/httprouter"
)

// HandleFleetFilterAdd godoc
// @Summary Add CAN filter for fleet
// @Description Add CAN filter for 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 config body common.CANFilter true "CAN filter"
// @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 [post]
func HandleFleetFilterAdd(w http.ResponseWriter, r *http.Request) {
	fleetFilterAdd.Handle(w, r)
}

var fleetFilterAdd = controllers.NewMongoUpdate(&fleetFilterAddHelper{})

type fleetFilterAddHelper struct{}

func (h *fleetFilterAddHelper) ParseUpdateURLParams(r *http.Request) interface{} {
	req := &mongo.Fleet{}

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

	return req
}

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

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

	return nil
}

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

func (h *fleetFilterAddHelper) 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 *fleetFilterAddHelper) QueryUpdate(filter interface{}, model interface{}) error {
	client, err := services.GetMongoClient()
	if err != nil {
		return err
	}

	if err = client.GetFleets().AddFilterToFleet(filter.(*mongo.Fleet).Name, model.(*common.CANFilter)); err != nil {
		return err
	}

	return ResetFleetVehiclesConfigCache(filter.(*mongo.Fleet).Name)
}

func ResetFleetVehiclesConfigCache(fleetName string) error {
	client, err := services.GetMongoClient()
	if err != nil {
		return err
	}

	vehicles, err := client.GetFleets().GetVehiclesForFleet(fleetName, "", &queries.PageQueryOptions{})
	if err != nil {
		return err
	}

	r := services.RedisClientPool().GetFromPool()
	defer r.Close()

	if err = cache.RemoveCacheConfigForVehicles(r, vehicles); err != nil {
		logger.Warn().Msgf("failed to remove cache config for vehicles: %v", err)
	}

	return nil
}
