using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Lada.Framework.Infrastructures.Helpers
{
    public static class UserHelper
    {
        public static CurrentUser GetCurrentUser(this ClaimsPrincipal user)
        {
            try
            {
                var userIdClaim = user.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub);
                if (userIdClaim == null)
                {
                    userIdClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                }

                var usernameClaim = user.Claims.FirstOrDefault(static c => c.Type == ClaimTypes.Name);
                var roles= user.Claims.Where(static c => c.Type == ClaimTypes.Role).Select(r => r.Value).ToList(); 
                return new CurrentUser()
                {
                    UserId = userIdClaim!= null ? int.Parse(userIdClaim.Value): 0,
                    UserName = usernameClaim!=null ? usernameClaim.Value : "",
                    Roles = roles
                };
            }

            catch (Exception)
            {
                return new CurrentUser();
            }
        }

        public static int GetUserId(this ClaimsPrincipal user)
        {
            try
            {
                var userIdClaim = user.Claims.FirstOrDefault(c => c.Type == "sub");
                if (userIdClaim == null)
                {
                    userIdClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                }

                return int.Parse(userIdClaim.Value);
            }
            catch (Exception)
            {

                return 0;
            }

        }

        public static string GetUsername(this ClaimsPrincipal user)
        {
            try
            {
                return user.FindFirst("preferred_username").Value;
            }
            catch (Exception)
            {

                return "";
            }
        }
    }
}
