package srv

import (
	"net/http"
	"strings"
)

type Req struct {
	r          *http.Request
	AppURL     string
	Path       string
	ParentPath string
	Pattern    string
	Ctx        map[string]any
}

func (req *Req) Construct(r *http.Request) {
	req.r = r
	req.AppURL = "/" + r.Host
	req.Path = r.RequestURI
	req.ParentPath = req.getParentPath()
	req.Pattern = req.getPattern()
	req.Ctx = make(map[string]any)
}

// The route pattern eg: /user
func (req *Req) getPattern() string {
	_, pattern := router.Handler(req.r)
	return pattern
}

func (req *Req) Cookie(name string) (string, error) {
	cookie, err := req.r.Cookie(name)
	if err != nil {
		return "", err
	}

	return cookie.Value, nil
}

func (req *Req) getParentPath() string {
	parentPath := ""
	arr := strings.Split(req.Path, "/")
	for i := 0; i < len(arr)-1; i++ {
		if arr[i] == "" {
			continue
		}
		parentPath += "/" + arr[i]
	}
	return parentPath
}
