using System.Security.Cryptography;
using System.Text;
using ColaFlow.Modules.Identity.Application.Services;

namespace ColaFlow.Modules.Identity.Infrastructure.Services;

public class SecurityTokenService : ISecurityTokenService
{
    public string GenerateToken()
    {
        var tokenBytes = new byte[32]; // 256 bits
        using var rng = RandomNumberGenerator.Create();
        rng.GetBytes(tokenBytes);

        // Base64URL encoding (URL-safe, no padding)
        return Convert.ToBase64String(tokenBytes)
            .Replace("+", "-")
            .Replace("/", "_")
            .TrimEnd('=');
    }

    public string HashToken(string token)
    {
        using var sha256 = SHA256.Create();
        var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(token));
        return Convert.ToBase64String(hashBytes);
    }

    public bool VerifyToken(string token, string hash)
    {
        var computedHash = HashToken(token);
        return CryptographicOperations.FixedTimeEquals(
            Encoding.UTF8.GetBytes(computedHash),
            Encoding.UTF8.GetBytes(hash));
    }
}
