package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/common/authproviders"
	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/fiskerinc/cloud-services/pkg/utils/urlhelper"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleUpdateManifestGet godoc
// @Summary Get update manifest
// @Description Get update manifest by id
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param id query string false "Update manifest id"
// @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 /manifest [get]
func HandleUpdateManifestGet(w http.ResponseWriter, r *http.Request) {
	manifest := common.UpdateManifest{
		ID: urlhelper.GetQueryInt64(r.URL.Query(), "id"),
	}

	if utils.AUTHGetProviderFromRequest(r) == authproviders.Magna {
		manifest.ManifestType = common.MagnaManifestUpdateType
	}

	err := validator.ValidateIDField(manifest.ID)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	um := services.GetDB().GetUpdateManifests()
	err = um.Load(&manifest)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	manifest.SortECUs()

	for i := range manifest.ECUs {
		manifest.ECUs[i].Scrub(0, false)
	}

	utils.RespJSON(w, http.StatusOK, &manifest)
}
