using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace LittleShop.Tests.Infrastructure;

public static class JwtTokenHelper
{
    public static string GenerateJwtToken(
        string userId = "test-user-id",
        string username = "testuser",
        string role = "User",
        int expirationMinutes = 60,
        string secretKey = "YourSuperSecretKeyThatIsAtLeast32CharactersLong!",
        string issuer = "LittleShop",
        string audience = "LittleShop")
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.UTF8.GetBytes(secretKey); // Use UTF8 encoding to match Program.cs
        
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, userId),
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, role)
        };

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.UtcNow.AddMinutes(expirationMinutes),
            Issuer = issuer,
            Audience = audience,
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(key), 
                SecurityAlgorithms.HmacSha256Signature)
        };

        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }

    public static string GenerateExpiredJwtToken(
        string userId = "test-user-id",
        string username = "testuser",
        string role = "User")
    {
        return GenerateJwtToken(userId, username, role, expirationMinutes: -60);
    }

    public static string GenerateInvalidJwtToken()
    {
        // Generate token with wrong secret key
        return GenerateJwtToken(secretKey: "WrongSecretKeyThatIsAtLeast32CharactersLong!");
    }

    public static string GenerateAdminJwtToken()
    {
        return GenerateJwtToken(
            userId: "admin-user-id",
            username: "admin",
            role: "Admin");
    }
}