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/loggerdataresp"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
)

// HandleUpdateManifestSUMSRxSwinsAdd godoc
// @Summary Add one or more RX Software ID Numbers (RxSWINs) for an update manifest version
// @Description Add one or more RX Software ID Numbers (RxSWINs) for an update manifest version and return them
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param version path string true "Update manifest version name"
// @Param swVersionRxSwins body common.SwVersionRxSwinCreate true "SwVersionRxSwin data"
// @Success 200 {object} []common.SwVersionRxSwin
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifest/sums/{version}/rxswins [post]
func HandleUpdateManifestSUMSRxSwinsAdd(w http.ResponseWriter, r *http.Request) {
	version := httprouter.ParamsFromContext(r.Context()).ByName("version")

	err := validator.ValidateStruct(common.SUMSVersion{Version: version})
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

	db := services.GetDB().GetSwVerRxSwin()
	for _, swVersionRxSwin := range svrsc.SwVersionRxSwins {
		swVersionRxSwin.Version = version
		_, err = db.Insert(&swVersionRxSwin)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
			return
		}
	}

	// Also add to other environments, as required
	for _, targetURL := range targetURLS {
		if !validator.ValidateURL(targetURL) || apiCreateToken == "" {
			break // No URL in MANIFEST_MIGRATE_URLS
		}

		otaService := services.NewOtaService(targetURL, apiCreateToken)

		resp, err := otaService.UpdateManifestSUMSRxSwinsAdd(version, svrsc)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
			return
		}

		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			utils.ForwardResponse(w, resp)
		}
	}

	utils.RespJSON(w, http.StatusOK, svrsc.SwVersionRxSwins)
}
