package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	orm "github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/julienschmidt/httprouter"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleUpdateManifestSUMSRxSwinsGet godoc
// @Summary Get all RX Software ID Numbers (RxSWINs) for a given manifest update manifest version
// @Description Get and return all RX Software ID Numbers (RxSWINs) for a given manifest update manifest version
// @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.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 [get]
func HandleUpdateManifestSUMSRxSwinsGet(w http.ResponseWriter, r *http.Request) {
	version := httprouter.ParamsFromContext(r.Context()).ByName("version")

	options, err := orm.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	if options.Order == "" {
		options.Order = "created_at DESC"
	}

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

	s := services.GetDB().GetSwVerRxSwin()

	allUpdateManifestVersionRxSwins, err := s.SelectByVersion(version, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	total, err := s.SelectCountByVersion(version)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data:  allUpdateManifestVersionRxSwins,
		Total: total,
	})
}
