package handlers

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

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

// HandleUpdateManifestSUMSUpdate godoc
// @Summary Update update manifest sums version
// @Description Update update manifest data
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id path int true "Update manifest id"
// @Param manifest body UpdateManifestVersion true "Manifest version"
// @Success 200 {object} common.UpdateManifest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifests/{id}/sums [put]
func HandleUpdateManifestSUMSUpdate(w http.ResponseWriter, r *http.Request) {
	var err error
	params := httprouter.ParamsFromContext(r.Context())
	req := UpdateManifestVersion{}
	req.ID, err = strconv.ParseInt(params.ByName("id"), 10, 64)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

	manifest := common.UpdateManifest{
		ID:   req.ID,
		SUMS: req.Version,
	}
	um := services.GetDB().GetUpdateManifests()
	result, err := um.AddSUMSVersion(&manifest)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	if result != nil && result.RowsAffected() == 0 && loggerdataresp.BadDataErrorResp(w, errors.New("cannot update. SUMS version already exists"), http.StatusBadRequest) {
		return
	}

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

type UpdateManifestVersion struct {
	ID      int64  `json:"-" validate:"required"`
	Version string `json:"version" validate:"required,sums_version"`
}
