/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package http

import (
	"net"
	"net/http"
	"path"
	"strings"
)

func RemoteAddr(r *http.Request) string {
	address, _, _ := net.SplitHostPort(r.RemoteAddr)
	if address != "localhost" && address != "127.0.0.1" && address != "::1" {
		return address
	}
	forwarded := r.Header.Get("X-Forwarded-For")
	if forwarded == "" {
		return address
	}
	ips := strings.Split(forwarded, ", ")
	forwarded = ips[0]
	if forwarded == "" {
		return address
	}
	return forwarded
}

func ShiftPath(p string) (head, tail string) {
	p = path.Clean("/" + p)
	if i := strings.IndexByte(p[1:], '/') + 1; i <= 0 {
		return p[1:], "/"
	} else {
		return p[1:i], p[i:]
	}
}

func MethodNotAllowed(w http.ResponseWriter, _ *http.Request, allowed ...string) {
	w.Header().Set("Allow", strings.Join(allowed, ", "))
	http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}

func Host(r *http.Request) string {
	host := r.Header.Get("X-Forwarded-Host")
	if host == "" {
		host = r.Host
	}
	return host
}

func IsHTTPS(r *http.Request) bool {
	return r.Header.Get("X-Forwarded-Proto") == "https"
}

func Protocol(r *http.Request) string {
	if IsHTTPS(r) {
		return "https"
	} else {
		return "http"
	}
}
