namespace GmRelay.DiscordBot.Rendering;

public static class DiscordEmbedUrls
{
    public static string? NormalizeHttpUrl(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
            return null;

        var candidate = value.Trim();
        if (IsSupportedHttpUrl(candidate, out var normalized))
            return normalized;

        if (candidate.Contains("://", StringComparison.Ordinal))
            return null;

        return IsSupportedHttpUrl($"https://{candidate}", out normalized)
            && HasPublicHost(normalized)
                ? normalized
                : null;
    }

    private static bool IsSupportedHttpUrl(string value, out string normalized)
    {
        normalized = string.Empty;

        if (!Uri.TryCreate(value, UriKind.Absolute, out var uri))
            return false;

        if (!string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)
            && !string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }

        normalized = uri.ToString();
        return true;
    }

    private static bool HasPublicHost(string value) =>
        Uri.TryCreate(value, UriKind.Absolute, out var uri)
        && uri.Host.Contains('.', StringComparison.Ordinal);
}
