package controllers

import (
	"net/http"

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

func NewMongoGetModel(helper MongoGetModelHelperInterface) *MongoHandleGetModel {
	return &MongoHandleGetModel{Helper: helper}
}

type MongoGetModelHelperInterface interface {
	ParseGetURLParams(r *http.Request) interface{}
	ValidatePK(model interface{}) error
	Query(filter interface{}) (interface{}, error)
}

type MongoHandleGetModel struct {
	Helper MongoGetModelHelperInterface
}

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

	item, err := h.Helper.Query(filter)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	} else if item == nil {
		loggerdataresp.BadDataErrorResp(w, err, http.StatusNotFound)
		return
	}

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

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