using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using SIGCM.Application.Interfaces;
using SIGCM.Domain.Entities;

namespace SIGCM.Infrastructure.Services;

public class TokenService : ITokenService
{
    private readonly IConfiguration _config;

    public TokenService(IConfiguration config)
    {
        _config = config;
    }

    public string GenerateToken(User user)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]!));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        // Especificamos explícitamente System.Security.Claims.Claim
        var claims = new[]
        {
        new System.Security.Claims.Claim(JwtRegisteredClaimNames.Sub, user.Username),
        new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, user.Role),
        new System.Security.Claims.Claim("Id", user.Id.ToString())
    };

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddHours(4),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
