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"
)

// HandleUpdateManifestAdd godoc
// @Summary Add update manifest
// @Description Upload update manifest
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param manifest body common.CreateUpdateManifest true "Manifest data"
// @Success 200 {object} common.CreateUpdateManifest
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /manifest [post]
func HandleUpdateManifestAdd(w http.ResponseWriter, r *http.Request) {
	m := common.CreateUpdateManifest{}
	err := httphandlers.ParseRequest(r, &m)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	um := services.GetDB().GetUpdateManifests()
	var manifest = common.UpdateManifest{
		Name:            m.Name,
		Version:         m.Version,
		Description:     m.Description,
		ReleaseNotes:    m.ReleaseNotes,
		RollbackEnabled: m.RollbackEnabled,
		Type:            m.Type,
		ManifestType:    m.ManifestType,
		Active:          m.Active,
		Country:         m.Country,
		PowerTrain:      m.PowerTrain,
		Restraint:       m.Restraint,
		Model:           m.Model,
		Trim:            m.Trim,
		Year:            m.Year,
		BodyType:        m.BodyType,
		UpdateDuration:  m.UpdateDuration,
		MaxAttempts:     m.MaxAttempts,
	}
	_, err = um.Insert(&manifest)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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