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

namespace BackOffice.Common.Utilities;

public interface ITokenHandler
{
    bool IsDifferent(string oldToken, string newToken);
    bool IsBlocked(string newToken);
    IEnumerable<Claim> GetUserClaims(string token);
}
public class TokenHandler : ITokenHandler
{
    public bool IsDifferent(string oldToken, string newToken)
    {
        oldToken = oldToken.Replace("\"", "");
        newToken = newToken.Replace("\"", "");
        var handler = new JwtSecurityTokenHandler();
        var oldJwtSecurityToken = handler.ReadJwtToken(oldToken);
        var newJwtSecurityToken = handler.ReadJwtToken(newToken);
        if (newJwtSecurityToken.Claims.Count() != oldJwtSecurityToken.Claims.Count())
            return true;

        int differences = 0;
        foreach (var claim in oldJwtSecurityToken.Claims)
        {
            if (claim.Type == "exp")
                continue;
            if (!newJwtSecurityToken.Claims.Any(x => x.Type == claim.Type && x.Value == claim.Value))
            {
                differences++;
            }
        }
        return differences > 0;
    }
    public bool IsBlocked(string newToken)
    {
        newToken = newToken.Replace("\"", "");
        var handler = new JwtSecurityTokenHandler();
        var newJwtSecurityToken = handler.ReadJwtToken(newToken);
        return newJwtSecurityToken.Claims.Any(x => x.Type == "IsBlocked" && x.Value == "True");
    }

    public IEnumerable<Claim> GetUserClaims(string token)
    {
        token = token.Replace("\"", "");
        var handler = new JwtSecurityTokenHandler();
        var newJwtSecurityToken = handler.ReadJwtToken(token);
        return newJwtSecurityToken.Claims;
    }
}
