package handlers

import (
	"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/utils/urlhelper"
	"github.com/fiskerinc/cloud-services/pkg/validator"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleUpdateManifestUpdate godoc
// @Summary Update update manifest
// @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 query int false "Update manifest id"
// @Param manifest body common.UpdateManifestUpdateRequest true "Manifest data"
// @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 [put]
func HandleUpdateManifestUpdate(w http.ResponseWriter, r *http.Request) {
	id := urlhelper.GetQueryInt64(r.URL.Query(), "id")
	err := validator.ValidateIDField(id)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	var mu common.UpdateManifestUpdateRequest
	err = httphandlers.ParseRequest(r, &mu)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	um := common.UpdateManifest{
		ID:              id,
		Name:            mu.Name,
		Type:            mu.Type,
		Active:          mu.Active,
		Country:         mu.Country,
		PowerTrain:      mu.PowerTrain,
		Restraint:       mu.Restraint,
		Model:           mu.Model,
		Trim:            mu.Trim,
		Year:            mu.Year,
		BodyType:        mu.BodyType,
		Env:             mu.Env,
		RollbackEnabled: mu.Rollback,
		SUMS:            mu.SUMS,
		UpdateDuration:  mu.UpdateDuration,
		MaxAttempts:     mu.MaxAttempts,
		ReleaseNotes:    mu.ReleaseNotes,
	}
	_, err = services.GetDB().GetUpdateManifests().Update(&um)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

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