package controllers

import (
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/utils"
	"github.com/go-pg/pg/v10/orm"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

func NewCreate(helper CreateHelperInterface) *HandleCreate {
	return &HandleCreate{Helper: helper}
}

type CreateHelperInterface interface {
	ParseRequest(r *http.Request, model interface{}) error
	QueryInsert(model interface{}) (orm.Result, error)
	NewModel() interface{}
}

type HandleCreate struct {
	Helper CreateHelperInterface
}

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

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

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