using Microsoft.AspNetCore.Http;
using System.Globalization;

namespace CarneiroTech.Services
{
    public interface ILanguageService
    {
        string GetCurrentLanguage(HttpContext context);
        void SetLanguage(HttpContext context, string language);
        string DetectBrowserLanguage(HttpContext context);
    }

    public class LanguageService : ILanguageService
    {
        private const string LanguageCookieName = "CarneiroTech_Language";
        private readonly string[] _supportedLanguages = { "pt", "en", "es" };
        private const string DefaultLanguage = "pt";

        public string GetCurrentLanguage(HttpContext context)
        {
            // 1. Check cookie first (user preference)
            if (context.Request.Cookies.TryGetValue(LanguageCookieName, out var cookieLanguage))
            {
                if (_supportedLanguages.Contains(cookieLanguage))
                {
                    return cookieLanguage;
                }
            }

            // 2. Detect from browser Accept-Language header
            var browserLanguage = DetectBrowserLanguage(context);
            if (!string.IsNullOrEmpty(browserLanguage) && _supportedLanguages.Contains(browserLanguage))
            {
                return browserLanguage;
            }

            // 3. Fallback to default (Portuguese)
            return DefaultLanguage;
        }

        public void SetLanguage(HttpContext context, string language)
        {
            if (_supportedLanguages.Contains(language))
            {
                var cookieOptions = new CookieOptions
                {
                    Expires = DateTimeOffset.UtcNow.AddYears(1),
                    HttpOnly = false, // Allow JavaScript to read for client-side logic
                    Secure = context.Request.IsHttps,
                    SameSite = SameSiteMode.Lax,
                    Path = "/"
                };

                context.Response.Cookies.Append(LanguageCookieName, language, cookieOptions);
            }
        }

        public string DetectBrowserLanguage(HttpContext context)
        {
            var acceptLanguageHeader = context.Request.Headers["Accept-Language"].ToString();

            if (string.IsNullOrEmpty(acceptLanguageHeader))
            {
                return string.Empty;
            }

            // Parse Accept-Language header
            // Format: "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6"
            var browserLanguages = acceptLanguageHeader
                .Split(',')
                .Select(lang => lang.Split(';')[0].Trim())
                .Select(lang => lang.Split('-')[0].ToLower()) // Get only language code (pt from pt-BR)
                .Distinct()
                .ToList();

            // Find first supported language
            foreach (var browserLang in browserLanguages)
            {
                if (_supportedLanguages.Contains(browserLang))
                {
                    return browserLang;
                }
            }

            return string.Empty;
        }
    }
}
