package controllers

import (
	"net/http"

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

func NewMongoUpdate(helper MongoUpdateHelperInterface) *MongoHandleUpdate {
	return &MongoHandleUpdate{Helper: helper}
}

type MongoUpdateHelperInterface interface {
	ParseUpdateURLParams(r *http.Request) interface{}
	ValidateFields(model interface{}) error
	NewModel() interface{}
	ParseRequestBody(r *http.Request, model interface{}) error
	QueryUpdate(filter interface{}, model interface{}) error
}

type MongoHandleUpdate struct {
	Helper MongoUpdateHelperInterface
}

func (h *MongoHandleUpdate) Handle(w http.ResponseWriter, r *http.Request) {
	filter := h.Helper.ParseUpdateURLParams(r)
	err := h.Helper.ValidateFields(filter)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	model := h.Helper.NewModel()
	err = h.Helper.ParseRequestBody(r, model)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}
	err = h.Helper.ValidateFields(model)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		logger.Warn().Err(err).Send()
		return
	}

	err = h.Helper.QueryUpdate(filter, model)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest, loggerdataresp.MongoUpdateErrorCheck) {
		return
	}

	logger.Info().Msgf("%+v", model)

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