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/validator"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

func NewGetList(helper GetListHelperInterface) *HandleGetList {
	return &HandleGetList{Helper: helper}
}

type GetListHelperInterface interface {
	ParseGetListQueryParams(r *http.Request) interface{}
	QueryCount(filter interface{}) (int, error)
	QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error)
	HasPK(filter interface{}) bool
}

type HandleGetList struct {
	Helper GetListHelperInterface
}

func (h *HandleGetList) Handle(w http.ResponseWriter, r *http.Request) {
	var total int

	filter := h.Helper.ParseGetListQueryParams(r)
	err := validator.ValidateNonRequired(filter)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

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

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

	if options.Offset == 0 && !h.Helper.HasPK(filter) {
		total, err = h.Helper.QueryCount(filter)
		if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
			return
		}
	}

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