package auth

import (
	"context"
	"net"
	"net/http"
	"strings"

	logicauth "gateway/internal/logic/auth"
)

// HandlerContext injects request audit metadata into the logic context.
// It accepts an explicit ctx (typically r.Context()) so the inheritance
// chain stays visible to static analysis (contextcheck).
func HandlerContext(ctx context.Context, r *http.Request) context.Context {
	return logicauth.WithRequestMeta(ctx, logicauth.RequestMeta{
		ClientIP:  clientIP(r),
		UserAgent: strings.TrimSpace(r.UserAgent()),
	})
}

func clientIP(r *http.Request) string {
	if r == nil {
		return ""
	}
	if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
		parts := strings.Split(xff, ",")
		return strings.TrimSpace(parts[0])
	}
	if xri := strings.TrimSpace(r.Header.Get("X-Real-IP")); xri != "" {
		return xri
	}
	host, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
	if err == nil {
		return host
	}
	return strings.TrimSpace(r.RemoteAddr)
}
