package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/utils"
)

// HandleVehicleStateMulti godoc
// @Summary Get state of a list of cars
// @Description Returns the states from a set of vins. Some vins may be missing in redis, or be invalid, but the other vins will still be successfully returned. Broken vin will be in the error list
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param data body []string true "List of vins"
// @Success 200 {object} JSONCarStateMultiMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /carstate_multi [post]
func HandleVehicleStateMulti(w http.ResponseWriter, r *http.Request) {
	var vins []string

	err := json.NewDecoder(r.Body).Decode(&vins)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	clientPool := services.RedisClientPool()
	twins, errorList := cache.GetVINListDigitalTwin(vins, clientPool)

	utils.RespJSON(w, http.StatusOK, &JSONCarStateMultiMessage{
		Data: twins,
		ErrorList: ErrorListToString(errorList),
	})
}

// There is no swagger doc conversion for the error type, so just converting to a string first
type JSONCarStateMultiMessage struct {
	Data map[string]common.CarState `json:"data"`
	ErrorList []string
}


func ErrorListToString(list []error)(res []string){
	for _, err := range list {
		res = append(res, err.Error())
	}
	return
}