using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using GxPress.Auth;
using GxPress.Result;
using Microsoft.IdentityModel.Tokens;

namespace GxPress.Api.Tools
{
    public static class TokenHelper
    {
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="jwtOptions"></param>
        /// <param name="claims"></param>
        /// <returns></returns>
        public static TokenResult BuildToken(JwtOptions jwtOptions, Claim[] claims)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expires = DateTime.Now.Add(jwtOptions.Expires);
            var token = new JwtSecurityToken(
                jwtOptions.Issuer,
                jwtOptions.Audience,
                claims,
                expires: expires,
                signingCredentials: credentials);

            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
            return new TokenResult
            {
                Type = "Bearer",
                Token = tokenStr,
                Expires = expires
            };
        }
    }
}