package handlers

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

	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/utils"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleUpdateManifestsArchive godoc
// @Summary Archive update manifests
// @Description Archive update manifests
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param manifest body common.UpdateManifestArchiveRequest true "Manifest data"
// @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 /manifests/archive [put]
func HandleUpdateManifestsArchive(w http.ResponseWriter, r *http.Request) {
	var payload common.UpdateManifestArchiveRequest
	err := httphandlers.ParseRequest(r, &payload)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	_, err = services.GetDB().
		GetUpdateManifests().
		Archive(payload.IDs, payload.Active)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	messageState := "Archived"
	if payload.Active {
		messageState = "Activated"
	}
	message := fmt.Sprintf("%s %d update manifests", messageState, len(payload.IDs))

	utils.RespJSON(w, http.StatusOK, common.JSONMessage{
		Message: message,
	})
}
