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"
)

// HandleTagsAppend godoc
// @Summary Append tags for cars.
// @Description Append 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 [post]
func HandleTagsAppend(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: req.Tags,
		}

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

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

}
