package handlers

import (
	"net/http"

	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

// HandleVehicleUpdate godoc
// @Summary Modify vehicle
// @Description Modify vehicle requires vehicle id
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin path string true "VIN"
// @Param car body common.UpdateCarRequest true "vehicle data"
// @Success 200 {object} common.UpdateCarRequest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle/{vin} [put]
func HandleVehicleUpdate(w http.ResponseWriter, r *http.Request) {
	var ucr common.UpdateCarRequest
	err := httphandlers.ParseRequest(r, &ucr)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	c := &common.Car{
		VIN:         ucr.VIN,
		ICCID:       ucr.ICCID,
		Year:        ucr.Year,
		Model:       ucr.Model,
		Trim:        ucr.Trim,
		Country:     ucr.Country,
		Powertrain:  ucr.Powertrain,
		Restraint:   ucr.Restraint,
		BodyType:    ucr.BodyType,
		Tags:        ucr.Tags,
		SUMSVersion: ucr.SUMSVersion,
	}

	_, err = services.GetDB().GetCars().Update(c)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	client, err := services.GetMongoClient()
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	v := &mongo.Vehicle{
		VIN:         ucr.VIN,
		LogLevel:    ucr.LogLevel,
		DebugMask:   ucr.DebugMask,
		DLTEnabled:  ucr.DLTEnabled,
		DLTLevel:    ucr.DLTLevel,
		IDPSEnabled: ucr.IDPSEnabled,
	}
	if ucr.CANBus != nil {
		if ucr.CANBus.DTCEnabled == nil {
			ucr.CANBus.DTCEnabled = elptr.ElPtr(true)
		}
		v.CANBus = *ucr.CANBus
	}

	err = client.GetVehicles().UpdateVehicle(v)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.MongoUpdateErrorCheck) {
		return
	}

	batch := redis.NewRedisBatchCommands()
	batch.Add("DEL", redis.CarConfigKey(ucr.VIN))

	if ucr.CANBus != nil {
		data := common.TRexConfigResponse{
			LogLevel: ucr.LogLevel,
			CANBus:   *ucr.CANBus,
		}
		if cache.ENABLE_DEBUG_MASK {
			data.DebugMask = ucr.DebugMask
		}
		data.DLTEnabled = ucr.DLTEnabled
		data.DLTLevel = ucr.DLTLevel

		err = batch.AddPublish(common.TRex.Key(ucr.VIN), common.Message{
			Handler: "config",
			Data:    data,
		})
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
			return
		}
	}

	conn := services.RedisClientPool().GetFromPool()
	defer conn.Close()
	_, err = conn.ExecuteBatch(batch)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, &ucr)
}
