using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Claims;

namespace MaUI
{
    public static class UserConntected
    {
        public static bool IsConnected { get; private set; } = false;
        public static string Token { get; private set; } = "";
        public static string ID { get; private set; } = "";
        public static string FirstName { get; private set; } = "";
        public static string LastName { get; private set; } = "";
        public static string Email { get; private set; } = "";
        public static List<string>? Roles { get; private set; } = new();

        public static void SetToken(string jwt)
        {
            Token = jwt;

            var handler = new JwtSecurityTokenHandler();
            var decodedToken = handler.ReadJwtToken(jwt);
            var identity = new ClaimsIdentity(decodedToken.Claims, "jwt");

            //FirstName = decodedToken.Claims.FirstOrDefault(c => c.Type == "FirstName")!.Value;
            //LastName = decodedToken.Claims.FirstOrDefault(c => c.Type == "LastName")!.Value;
            //Email = decodedToken.Claims.FirstOrDefault(c => c.Type == "Email")!.Value;
            ID = decodedToken.Claims.FirstOrDefault(c => c.Type == "ID")!.Value;
            IsConnected = true;

            var user = new ClaimsPrincipal(identity);

            Roles = user.FindAll(ClaimTypes.Role).Select(r => r.Value).ToList();

            SecureStorage.SetAsync("authToken", jwt); // Stocke le token
        }
    }

    public class AuthorizedHttpClientHandler : DelegatingHandler
    {
        public AuthorizedHttpClientHandler()
        {
            InnerHandler = new HttpClientHandler(); 
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var token = await SecureStorage.GetAsync("authToken");
            if (!string.IsNullOrEmpty(token))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            }
            return await base.SendAsync(request, cancellationToken);
        }
    }

    public class ApiService
    {
        private readonly HttpClient _httpClient;
        private readonly HttpClient _httpClientLogin;

        #region Constructeur
        public ApiService()
        {
            _httpClientLogin = new HttpClient { BaseAddress = new Uri("https://localhost:7008") };
            _httpClient = new HttpClient(new AuthorizedHttpClientHandler());
            _httpClient.BaseAddress = new Uri("https://localhost:7008");
        }
        #endregion

        #region Service Create
        public async Task<bool> Create_Async<T>(string url, T data)
        {
            var response = await _httpClient.PostAsJsonAsync(url, data);
            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return false;
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
            {
                throw new Exception("Internal server error");
            }
            return response.IsSuccessStatusCode;
        }
        #endregion

        #region Service Update
        public async Task<bool> Update_Async<T>(string url, T data)
        {
            var response = await _httpClient.PutAsJsonAsync(url, data);
            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return false;
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
            {
                throw new Exception("Internal server error");
            }
            return response.IsSuccessStatusCode;
        }
        #endregion

        #region Service Delete
        public async Task<bool> Delete_Async<T>(string url)
        {
            var response = await _httpClient.DeleteAsync(url);
            if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return false;
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
            {
                throw new Exception("Internal server error");
            }
            return response.IsSuccessStatusCode;
        }
        #endregion

        #region Service GetAll
        public async Task<T[]> GetAll_Async<T>(string url)
        {
            // Charger les items
            var response = await _httpClient.GetFromJsonAsync<T[]>(url);
            return response ?? Array.Empty<T>();
        }
        #endregion

        #region Service EnvoiRequete
        public async Task<string> EnvoiRequete<T>(string url, T data)
        {
            var response = await _httpClient.PostAsJsonAsync(url, data);

            if (!response.IsSuccessStatusCode)
                return $"Erreur : {response.StatusCode}";

            // lire le contenu JSON renvoyé
            var result = await response.Content.ReadAsStringAsync();
            return result;
        }
        #endregion

        #region Service GetById
        /* A IMPLEMENTER SI BESOIN
        public async Task<T> GetById_Async<T>(string url)
        {

        }
        */
        #endregion

        #region AuthLogin
        public async Task<bool> Connexion(LoginModel item)
        {
            try
            {
                string url= $"api/auth/login";
                var response = await _httpClientLogin.PostAsJsonAsync(url, item);
                response.EnsureSuccessStatusCode();
                var loginResponse = await response.Content.ReadFromJsonAsync<LoginResponse>();
                if (loginResponse is not null && !string.IsNullOrWhiteSpace(loginResponse.Token))
                {
                    UserConntected.SetToken(loginResponse.Token);
                }
                else 
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
    }
}


