package handlers

import (
	"errors"
	"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"
)

// HandleUpdateManifestSUMSAdd godoc
// @Summary Create new update manifest versions
// @Description Create and save new update manifest versions, and return them
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param SUMSVersion body common.SUMSVersionCreate true "SwVersionRxSwin data"
// @Success 200 {object} []common.SUMSVersion
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifest/sums [post]
func HandleUpdateManifestSUMSAdd(w http.ResponseWriter, r *http.Request) {
	svc := common.SUMSVersionCreate{}
	err := httphandlers.ParseRequest(r, &svc)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	if len(svc.SUMSVersions) < 1 {
		loggerdataresp.BadDataErrorResp(w, errors.New("called /manifest/sums/ POST with no sums versions to add"), http.StatusBadRequest)
	}

	for _, sumsVersion := range svc.SUMSVersions {
		err = validator.ValidateStruct(sumsVersion)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
			return
		}
	}

	db := services.GetDB().GetUpdateManifestVersions()
	for _, sumsVersion := range svc.SUMSVersions {
		_, err = db.Insert(&sumsVersion)
		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.UpdateManifestSUMSAdd(svc)
		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, svc.SUMSVersions)
}
