using System.Net;

namespace Ehwrj.Core.Services;

public static class LoopbackGuard
{
    public static void EnsureLoopbackHttp(Uri uri, string parameterName)
    {
        if (!IsLoopbackHttp(uri))
        {
            throw new ArgumentException("Only HTTP loopback addresses are allowed.", parameterName);
        }
    }

    public static bool IsLoopbackHttp(Uri uri)
    {
        return uri.IsAbsoluteUri &&
               string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) &&
               uri.IsLoopback;
    }

    public static bool IsLoopbackHost(string host)
    {
        if (string.IsNullOrWhiteSpace(host))
        {
            return false;
        }

        if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        return IPAddress.TryParse(host, out var address) && IPAddress.IsLoopback(address);
    }
}

