package controllers

import (
	"net/http"

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

func NewDelete(helper DeleteHelperInterface) *HandleDelete {
	return &HandleDelete{Helper: helper}
}

type DeleteHelperInterface interface {
	ParseDeleteQueryParams(r *http.Request) interface{}
	QueryDelete(req interface{}) (orm.Result, error)
	ValidatePK(model interface{}) error
}

type HandleDelete struct {
	Helper DeleteHelperInterface
}

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

	result, err := h.Helper.QueryDelete(filter)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	if result != nil && result.RowsAffected() == 0 {
		loggerdataresp.BadDataErrorResp(w, errors.New("Nothing deleted"), http.StatusNotFound)
		return
	}

	utils.RespJSON(w, http.StatusOK, common.JSONMessage{
		Message: "Deleted",
	})
}
