package handlers

import (
	"context"
	"net/http"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	redis "github.com/fiskerinc/cloud-services/pkg/redisv2"
	"github.com/fiskerinc/cloud-services/pkg/validator"
)

// HandleGetCarsHMIKey godoc
// @Summary Returns HMI session ID from Redis
// @Description If you don't know what this is, don't call it. It's that simple
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin query string true "VIN"
// @Success 200 {object} string
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 404 {object} common.JSONError "Not Found"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /cars/hmi_key [get]
func HandleGetCarsHMIKey(w http.ResponseWriter, r *http.Request) {
	queryParams := r.URL.Query()
	vin := queryParams.Get("vin")
	ok := validator.ValidateVINSimple(vin)
	if !ok {
		loggerdataresp.BadDataErrorResp(w, ErrInvalidVIN, http.StatusBadRequest)
		return
	}

	rd := services.GetRedisV2Client()
	res := rd.Client.Get(context.Background(), redis.HMISessionKey(vin))
	sessionOrSalt, err := res.Result()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Failed To Get SessionOrSalt"))
		return
	}

	w.Write([]byte(sessionOrSalt))
}