package utils

import (
	"net/http"
	"strings"
)

// ClientIP returns a single client IP address (left-most X-Forwarded-For entry).
func ClientIP(req *http.Request) string {
	if xff := strings.TrimSpace(req.Header.Get("X-Forwarded-For")); xff != "" {
		return strings.TrimSpace(strings.Split(xff, ",")[0])
	}
	return singleClientIP(req)
}

// ClientForwardedFor returns the full X-Forwarded-For header when present,
// matching legacy PHP HTTP_X_FORWARDED_FOR passthrough to the AdMedia feed.
// Falls back to a single client IP when the header is absent.
func ClientForwardedFor(req *http.Request) string {
	if xff := strings.TrimSpace(req.Header.Get("X-Forwarded-For")); xff != "" {
		return xff
	}
	return singleClientIP(req)
}

func singleClientIP(req *http.Request) string {
	if ip := strings.TrimSpace(req.Header.Get("X-Real-IP")); ip != "" {
		return ip
	}
	if ip := strings.TrimSpace(req.Header.Get("X-Client-IP")); ip != "" {
		return ip
	}
	return GetHostWithoutPort(req.RemoteAddr)
}
