using System.Net;

namespace YMhut.Box.Core.Net;

public static class HttpRedirectResolver
{
    public static async Task<Uri> ResolveAsync(
        Uri uri,
        HttpMessageInvoker client,
        int maxRedirects = 8,
        CancellationToken cancellationToken = default)
    {
        var current = uri;
        for (var redirect = 0; redirect < Math.Max(1, maxRedirects); redirect++)
        {
            using var request = new HttpRequestMessage(HttpMethod.Get, current);
            using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
            if (!IsRedirect(response.StatusCode))
            {
                response.EnsureSuccessStatusCode();
                return current;
            }

            var location = response.Headers.Location;
            if (location is null)
            {
                return current;
            }

            current = location.IsAbsoluteUri ? location : new Uri(current, location);
        }

        return current;
    }

    private static bool IsRedirect(HttpStatusCode statusCode)
    {
        return statusCode is HttpStatusCode.Moved or
            HttpStatusCode.Redirect or
            HttpStatusCode.RedirectMethod or
            HttpStatusCode.TemporaryRedirect or
            HttpStatusCode.PermanentRedirect;
    }
}
