package handlers

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

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

// HandleUpdateManifestECUAdd godoc
// @Summary Add update manifest ecu
// @Description Create update manifest ECU
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param manifest body UpdateManifestECURequest true "Manifest ECU data"
// @Success 200 {object} common.UpdateManifestECU
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifestecu [post]
func HandleUpdateManifestECUAdd(w http.ResponseWriter, r *http.Request) {
	ecu := common.UpdateManifestECU{}

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

	um := services.GetDB().GetUpdateManifests()
	ecu.Files = nil
	_, err = um.ECUInsert(&ecu)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

type UpdateManifestECURequest struct {
	UpdateManifestID int64  `json:"manifest_id,omitempty"`
	ECU              string `json:"name,omitempty"`
	Version          string `json:"version"`
	HWVersions       string `json:"hw_versions,omitempty"`
	SelfDownload     bool   `json:"self_download,omitempty"`
	Mode             string `json:"mode,omitempty"`
	InstallPriority  int    `json:"install_priority,omitempty" pg:"install_priority"`
}
