package api

import (
	"net"
	"strings"

	"github.com/gin-gonic/gin"
)

func publicHostFromRequest(c *gin.Context) string {
	host := c.Request.Host
	if h := firstForwarded(c.GetHeader("X-Forwarded-Host")); h != "" {
		host = h
	}
	if host == "" {
		return "https://vantage.example.com"
	}
	return schemeFor(c, host) + "://" + host
}

func schemeFor(c *gin.Context, host string) string {
	if p := firstForwarded(c.GetHeader("X-Forwarded-Proto")); p != "" {
		return p
	}
	if c.Request.TLS != nil {
		return "https"
	}
	if isLoopback(host) {
		return "http"
	}
	return "https"
}

func firstForwarded(v string) string {
	if v == "" {
		return ""
	}
	return strings.TrimSpace(strings.Split(v, ",")[0])
}

func isLoopback(host string) bool {
	h, _, err := net.SplitHostPort(host)
	if err != nil {
		h = host
	}
	if h == "localhost" || strings.HasSuffix(h, ".localhost") {
		return true
	}
	ip := net.ParseIP(h)
	return ip != nil && ip.IsLoopback()
}
