using Lactose.Configuration;
using Lactose.Models;
using Lactose.Repositories;
using Lactose.Utils;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Concurrent;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Lactose.Services;

public interface ITokenService {
    string GenerateToken(ClaimsIdentity identity, int expireTime);
    string GenerateToken(int expireTime);
}

public class TokenService (
    IOptions<SignKeyConfiguration> signKey
    ) : ITokenService {
    
    public const int BaseExpirationTime = 30;

    readonly TokenGenerator tokenGenerator = new TokenGenerator(
        new SigningCredentials(signKey.Value.GetSecurityKey(), SecurityAlgorithms.HmacSha256Signature),
        descriptor => {
            var handler = new JwtSecurityTokenHandler();
            var token   = handler.CreateToken(descriptor);
            return handler.WriteToken(token);
        }
    );
    
    public string GenerateToken(ClaimsIdentity identity, int expireTime = BaseExpirationTime) => tokenGenerator.Generate(identity, expireTime);
    
    public string GenerateToken(int expireTime = BaseExpirationTime) => tokenGenerator.Generate(expireTime);
}
