using FuelServer.Core;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace DFS.Core.Mvc.Middlewares
{
    public static class JwtValidator
    {
        private static string _secretKey = ConstKey.JwtKey;
        private static string _issuer = ConstKey.JwtIssuer;
        private static string _audience = ConstKey.JwtAudience;


        public static bool ValidateToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                // 将密钥转换为字节数组
                var key = Encoding.ASCII.GetBytes(_secretKey);

                // 设置 Token 验证参数
                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true, // 验证签名
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = true, // 验证签发者
                    ValidIssuer = _issuer,
                    ValidateAudience = true, // 验证受众
                    ValidAudience = _audience,
                    ValidateLifetime = true, // 验证过期时间
                    ClockSkew = TimeSpan.Zero // 不允许时间偏差
                };

                // 验证 Token
                ClaimsPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);

                // 如果验证成功，返回 true
                return true;
            }
            catch (SecurityTokenExpiredException)
            {
                // Token 已过期
                Console.WriteLine("Token has expired.");
                return false;
            }
            catch (SecurityTokenValidationException)
            {
                // Token 验证失败（签名无效、签发者或受众不匹配等）
                Console.WriteLine("Token validation failed.");
                return false;
            }
            catch (Exception ex)
            {
                // 其他异常
                Console.WriteLine($"An error occurred: {ex.Message}");
                return false;
            }
        }
    }
}
