package mutilimp

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/go-chi/chi/v5"
	"go.mongodb.org/mongo-driver/v2/bson"
)

func addParam(base string, param string) string {
	base = strings.TrimSuffix(base, "/")
	return fmt.Sprintf("%s/{%s}", base, param)
}

func _ref(param string) string {
	return param + "_ref"
}

func getParam(r *http.Request, paramName string) string {
	return chi.URLParam(r, paramName)
}

type ParamHelper struct {
	t string
}

func (ph *ParamHelper) Name() string {
	return ph.t
}

func (ph *ParamHelper) RefName() string {
	return _ref(ph.Name())
}

func (ph *ParamHelper) GetID(r *http.Request) string {
	return getParam(r, ph.RefName())
}

func (ph *ParamHelper) GetRef(r *http.Request) (bson.ObjectID, error) {
	return bson.ObjectIDFromHex(ph.GetID(r))
}

func (ph *ParamHelper) AddRef(base string) string {
	return addParam(base, ph.RefName())
}

func CreateImp(resource string) *ParamHelper {
	return &ParamHelper{t: resource}
}
