using Microsoft.AspNetCore.Localization;

namespace QRRapidoApp.Providers
{
    public class CustomRouteDataRequestCultureProvider : IRequestCultureProvider
    {
        public Task<ProviderCultureResult?> DetermineProviderCultureResult(HttpContext httpContext)
        {
            // First check if the middleware has already determined the culture (e.g. for static routes like /es/pix)
            if (httpContext.Items.TryGetValue("Culture", out var cultureItem) && cultureItem is string cultureFromMiddleware)
            {
                var supportedCultures = new[] { "pt-BR", "es", "en" };
                if (supportedCultures.Contains(cultureFromMiddleware))
                {
                    return Task.FromResult<ProviderCultureResult?>(new ProviderCultureResult(cultureFromMiddleware, cultureFromMiddleware));
                }
            }

            // Fallback to route data (standard routing)
            var routeValues = httpContext.GetRouteData()?.Values;
            if (routeValues != null && routeValues.TryGetValue("culture", out var cultureValue))
            {
                var culture = cultureValue?.ToString();
                if (!string.IsNullOrEmpty(culture))
                {
                    // Map the supported cultures
                    var supportedCultures = new[] { "pt-BR", "es", "en" };
                    if (supportedCultures.Contains(culture))
                    {
                        return Task.FromResult<ProviderCultureResult?>(new ProviderCultureResult(culture, culture));
                    }
                }
            }

            return Task.FromResult<ProviderCultureResult?>(null);
        }
    }
}