package controllers

import (
	"net/http"

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

func NewGetModel(helper GetModelHelperInterface) *HandleGetModel {
	return &HandleGetModel{Helper: helper}
}

type GetModelHelperInterface interface {
	ParseGetModelParams(r *http.Request) interface{}
	QueryLoad(model interface{}) error
	HasPK(model interface{}) bool
}

type HandleGetModel struct {
	Helper GetModelHelperInterface
}

func (h *HandleGetModel) Handle(w http.ResponseWriter, r *http.Request) {
	item := h.Helper.ParseGetModelParams(r)
	hasPK := h.Helper.HasPK(item)
	if !hasPK {
		loggerdataresp.BadDataErrorResp(w, ErrorPKRequired, http.StatusBadRequest)
		return
	}

	err := h.Helper.QueryLoad(item)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

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