using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VentaUniformes.Application.Interfaces.External;

namespace VentaUniformes.External.ValidateTokenJwt
{
    public class ValidateTokenJwtService: IValidateTokenService
    {
        private readonly IConfiguration _config;
        public ValidateTokenJwtService(IConfiguration config)
        {
            _config = config;
        }
        public bool ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_config["SecretKeyJwt"] ?? ""); // La clave secreta que usaste para firmar el token
            try
            {
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = _config["IssuerJWT"],
                    ValidAudience = _config["AudienceJwt"],
                    IssuerSigningKey = new SymmetricSecurityKey(key)
                }, out SecurityToken validatedToken);

                // Si el token es válido, regresa true
                return true;
            }
            catch
            {
                // Si el token no es válido, regresa false
                return false;
            }
        }
    }
}
