package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	"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"
	"github.com/pkg/errors"
)

// HandleUpdateManifestSUMSDelete godoc
// @Summary Delete a SUMS version number
// @Description Delete a SUMS version number
// @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"
// @Success 200 {object} common.JSONMessage
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifest/sums/{version} [delete]
func HandleUpdateManifestSUMSDelete(w http.ResponseWriter, r *http.Request) {
	params := httprouter.ParamsFromContext(r.Context())

	version := params.ByName("version")

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

	result, err := services.GetDB().GetUpdateManifestVersions().Delete(&common.SUMSVersion{Version: version})
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	if result != nil && result.RowsAffected() == 0 && loggerdataresp.BadDataErrorResp(w, errors.New("cannot delete. SUMS version does not exist"), http.StatusBadRequest) {
		return
	}

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

		otaService := services.NewOtaService(targetURL, apiDeleteToken)

		resp, err := otaService.UpdateManifestSUMSDelete(version)
		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, common.JSONMessage{
		Message: "Deleted",
	})
}
