package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"otaupdate/services"
	"strconv"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/common/actionlogger"
	"github.com/fiskerinc/cloud-services/pkg/common/carupdatestatus"
	"github.com/fiskerinc/cloud-services/pkg/common/handlers"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	re "github.com/gomodule/redigo/redis"
	"github.com/julienschmidt/httprouter"
)

// HandleCarUpdateVehicleCancel godoc
// @Summary Cancel car update on vehicle
// @Description Cancel a rogue car update on a vehicle that's not found on cloud.
// A car update may not be found in cloud following physical vehicle maintenance.
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id path string true "Car update id to cancel"
// @Param vin query string true "VIN of vehicle to send to"
// @Success 200 {object} common.JSONMessage "Request result"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /carupdate/{id}/vehicle-cancel [post]
func HandleCarUpdateVehicleCancel(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())
	id, err := strconv.ParseInt(params.ByName("id"), 10, 64)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	vin := r.URL.Query().Get("vin")
	ok := validator.ValidateVINSimple(vin)
	if !ok {
		loggerdataresp.BadDataErrorResp(w, ErrInvalidVIN, http.StatusBadRequest)
		return
	}

	req := common.CarUpdateRequest{
		CarUpdateID: id,
	}

	err = validator.ValidateStruct(req)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	alDB := services.GetDB().GetActionLog()
	go func() {
		actionLog := actionlogger.ActionLog{
			VIN:            vin,
			Action:         actionlogger.CarUpdate,
			UserIdentifier: httphandlers.GetClientID(r),
			CallLocation:   "github.com/fiskerinc/cloud-services/services/ota_update_go/handlers/carupdate_vehicle_cancel.go",
			Description:    fmt.Sprintf("car update id: %d", req.CarUpdateID),
		}

		err = alDB.Insert(actionLog)
		if err != nil {
			logger.Err(err).Msg("failed to insert action log inside HandleCarUpdateVehicleCancel")
		}
	}()

	cu := &common.CarUpdate{
		ID:  id,
		VIN: vin,
	}

	carupdates := services.GetDB().GetCarUpdates()
	_, err = carupdates.SelectByID(req.CarUpdateID)
	if err == nil {
		err = fmt.Errorf("car update was found in cloud, use /carupdate/%d/cancel", req.CarUpdateID)
	} else {
		err = nil
	}

	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	err = sendCancelUpdate(req, cu)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONMessage{
		Message: "OK",
	})
}

func sendCancelUpdate(req common.CarUpdateRequest, cu *common.CarUpdate) (err error) {
	client := services.RedisClientPool().GetFromPool()
	defer client.Close()

	key := redis.CarUpdateStatusHashKey(req.CarUpdateID)
	msg, err := json.Marshal(common.Message{
		Handler: handlers.UpdateManifestCancel,
		Data:    req,
	})

	batch := redis.NewRedisBatchCommands()
	batch.Add(re.Args{}.Add("HSET").Add(key).AddFlat(common.CarUpdateProgress{
		CarUpdateID: req.CarUpdateID,
		Status:      carupdatestatus.ManifestCancelPending,
	})...)
	batch.Add("EXPIRE", key, 3600)
	batch.Add("RPUSH", redis.QueueKey(common.TRex.Key(cu.VIN)), msg)
	batch.Add("EXPIRE", redis.QueueKey(common.TRex.Key(cu.VIN)), 3600)
	batch.Add("RPUSH", redis.QueueKey(common.HMI.Key(cu.VIN)), msg)
	batch.Add("EXPIRE", redis.QueueKey(common.HMI.Key(cu.VIN)), 3600)

	_, err = client.ExecuteBatch(batch)
	if err != nil {
		return
	}

	return
}
