package aapitemplate

import (
	"encoding/json"
	"net/http"

	"github.com/tech/sendico/pkg/db/repository"
	"github.com/tech/sendico/pkg/db/repository/builder"
	"github.com/tech/sendico/server/interface/api/srequest"
)

type ReorderRequestProcessor func(r *http.Request) (*srequest.ReorderX, builder.Query, error)

type ReorderConfig struct {
	DB           ReorderDB
	ReqProcessor ReorderRequestProcessor
}

func (cfg *AAPIConfig) WithReorderHandler(reorder ReorderConfig) *AAPIConfig {
	cfg.Reorder = &reorder
	if cfg.Reorder.ReqProcessor == nil {
		cfg.Reorder.ReqProcessor = defaultRequestProcessor
	}
	return cfg
}

func defaultRequestProcessor(r *http.Request) (*srequest.ReorderX, builder.Query, error) {
	var req srequest.ReorderXDefault
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return nil, nil, err
	}
	return &req.ReorderX, repository.OrgFilter(req.ParentRef), nil
}
