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 NewUpdate(helper UpdateHelperInterface) *HandleUpdate {
	return &HandleUpdate{Helper: helper}
}

type UpdateHelperInterface interface {
	ParseRequest(r *http.Request, model interface{}) error
	QueryUpdate(model interface{}) (orm.Result, error)
	NewModel() interface{}
	ValidatePK(model interface{}) error
}

type HandleUpdate struct {
	Helper UpdateHelperInterface
}

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

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

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

func (h *HandleUpdate) ParseRequest(r *http.Request, model interface{}) error {
	err := h.Helper.ParseRequest(r, model)
	if err != nil {
		return err
	}

	return h.Helper.ValidatePK(model)
}
