package handlers

import (
	"errors"
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	e "github.com/fiskerinc/cloud-services/pkg/mongo/error"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
)

// HandleFleetUpdate godoc
// @Summary Update fleet
// @Description Update 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 mongo.Fleet true "Fleet data"
// @Success 200 {object} mongo.Fleet
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleet/{name} [put]
func HandleFleetUpdate(w http.ResponseWriter, r *http.Request) {
	fleetUpdate.Handle(w, r)
}

var fleetUpdate = controllers.NewMongoUpdate(&fleetUpdateHelper{})

type fleetUpdateHelper struct {
	fleetHelper
}

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

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

	return req
}

func (h *fleetUpdateHelper) 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 *fleetUpdateHelper) ParseRequestBody(r *http.Request, model interface{}) error {
	err := httphandlers.ParseRequest(r, model)
	if err != nil {
		return err
	}

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

	return nil
}

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

	flt := model.(*mongo.Fleet)
	if flt.CANBus.DTCEnabled == nil {
		flt.CANBus.DTCEnabled = elptr.ElPtr(true)
	}

	err = client.GetFleets().UpdateFleet(filter.(*mongo.Fleet), flt)
	if err != nil {
		return err
	}

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

	batch := redis.NewRedisBatchCommands()

	for _, fleetVIN := range fleetVINs {
		v := &mongo.Vehicle{VIN: fleetVIN, LogLevel: flt.LogLevel, CANBus: flt.CANBus, DebugMask: flt.DebugMask, IDPSEnabled: flt.IDPSEnabled}

		err = client.GetVehicles().UpdateVehicle(v)
		if err != nil && errors.Is(err, e.ErrInvalidNumberOfDocs) {
			logger.At(logger.Warn(), fleetVIN, "mongodb").Err(err).Send()
			continue
		} else if err != nil {
			return err
		}

		batch.Add("DEL", redis.CarConfigKey(fleetVIN))

		if flt.CANBus.DTCEnabled != nil {
			data := common.TRexConfigResponse{
				LogLevel: flt.LogLevel,
				CANBus:   flt.CANBus,
			}
			if cache.ENABLE_DEBUG_MASK {
				data.DebugMask = flt.DebugMask
			}

			data.IDPSEnabled = flt.IDPSEnabled

			err = batch.AddPublish(common.TRex.Key(fleetVIN), common.Message{
				Handler: "config",
				Data:    data,
			})
			if err != nil {
				return err
			}
		}
	}

	conn := services.RedisClientPool().GetFromPool()
	defer conn.Close()
	_, err = conn.ExecuteBatch(batch)
	if err != nil {
		return err
	}

	return nil
}
