package controllers

import (
	"net/http"

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

func NewMongoGetList(helper MongoGetListHelperInterface) *MongoHandleGetList {
	return &MongoHandleGetList{Helper: helper}
}

type MongoGetListHelperInterface interface {
	NewModel() interface{}
	ParseGetListURLParams(r *http.Request, model interface{})
	ParseGetListQueryParams(r *http.Request, model interface{})
	ValidateStruct(model interface{}) error
	QueryCount(filter interface{}) (int64, error)
	QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error)
}

type MongoHandleGetList struct {
	Helper MongoGetListHelperInterface
}

func (h *MongoHandleGetList) Handle(w http.ResponseWriter, r *http.Request) {
	filter := h.Helper.NewModel()
	h.Helper.ParseGetListURLParams(r, filter)
	h.Helper.ParseGetListQueryParams(r, filter)
	err := h.Helper.ValidateStruct(filter)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	options, err := queries.ParsePageQuery(r)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	items, err := h.Helper.QuerySelect(filter, options)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	var total int64
	if options.Offset == 0 && options.Limit != 0 {
		total, err = h.Helper.QueryCount(filter)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
			return
		}
	}

	utils.RespJSON(w, http.StatusOK, common.JSONDBQueryResult{
		Data:  items,
		Total: int(total),
	})
}
