package controllers

import (
	"net/http"

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

func NewMongoCreate(helper MongoCreateHelperInterface) *MongoHandleCreate {
	return &MongoHandleCreate{Helper: helper}
}

type MongoCreateHelperInterface interface {
	QueryInsert(model interface{}) error
	NewModel() interface{}
	ValidatePK(model interface{}) error
}

type MongoHandleCreate struct {
	Helper MongoCreateHelperInterface
}

func (h *MongoHandleCreate) Handle(w http.ResponseWriter, r *http.Request) {
	model := h.Helper.NewModel()
	err := httphandlers.ParseRequest(r, model)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

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

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