package handlers

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

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

// HandleTagsUpdate godoc
// @Summary Update tags for cars.
// @Description Replace the tags for the provided set of car VINs.
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param data body TagsUpdateRequest true "Update tags"
// @Success 200 {object} common.JSONMessage "Updated tags"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /tags [put]
func HandleTagsUpdate(w http.ResponseWriter, r *http.Request) {
	var req TagsUpdateRequest

	err := httphandlers.ParseRequest(r, &req)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	for _, vin := range req.VINs {
		c := &common.Car{
			VIN:  vin,
			Tags: RemoveDuplicateTags(req.Tags),
		}

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

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

type TagsUpdateRequest struct {
	Tags []string `json:"tags" validate:"required,dive,required"`
	VINs []string `json:"vins" validate:"required,gte=0,lte=100,dive,vin"`
}

func RemoveDuplicateTags(tags []string) []string {
	uniqueMap := make(map[string]struct{})

	// Iterate over the original slice
	for _, value := range tags {
		uniqueMap[value] = struct{}{}
	}

	// Create a new slice with unique elements
	uniqueTags := make([]string, 0, len(uniqueMap))
	for key := range uniqueMap {
		uniqueTags = append(uniqueTags, key)
	}

	return uniqueTags
}
