using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

using CommonHelpers;

namespace BookRegistry.Server {

//**************************************************************************************************
static class JWT {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

public static JwtInfo Generate( string userName, string roleName,
                                bool refreshTokenType = false ) =>
   Generate( userName, roleName,
      refreshTokenType ? AuthTokenType.Refresh : AuthTokenType.Access );

public static JwtInfo Generate(string userName,string roleName,AuthTokenType tokenType)
{
   var claims = new List<Claim>
   {
      new Claim( ClaimsIdentity.DefaultNameClaimType, userName ),
      new Claim( ClaimsIdentity.DefaultRoleClaimType, roleName )
   };
   var identity = new ClaimsIdentity(
      claims, "Token", ClaimsIdentity.DefaultNameClaimType,
      ClaimsIdentity.DefaultRoleClaimType );

   var nowUtc = DateTime.UtcNow;
   var lifetimePeriod = AuthOptions.GetLifetimePeriod( tokenType );
   var expirationUtc = nowUtc.Add( lifetimePeriod );
   var jwt = new JwtSecurityToken(
      issuer: AuthOptions.Issuer,
      audience: AuthOptions.Audience,
      notBefore: nowUtc,
      claims: identity.Claims,
      expires: expirationUtc,
      signingCredentials: new SigningCredentials(
         AuthOptions.GetSymmetricSecurityKey(),
         SecurityAlgorithms.HmacSha256 )
   );
   string encodedJwt = new JwtSecurityTokenHandler().WriteToken( jwt );

   return new JwtInfo( encodedJwt, identity.Name.NN(), roleName, expirationUtc );
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
} // JWT
//**************************************************************************************************

} // BookRegistry.Server
