using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Microsoft.Extensions.Options;

namespace Jiaowu.Api.Tests;

public sealed class TokenServiceTests
{
    [Fact]
    public void Token_contains_identity_and_roles()
    {
        var options = Options.Create(new JwtOptions
        {
            Issuer = "tests",
            Audience = "tests-web",
            Key = "a-test-signing-key-that-is-at-least-32-bytes-long"
        });
        var user = new ApplicationUser
        {
            Id = Guid.NewGuid(),
            UserName = "teacher01",
            DisplayName = "陈老师"
        };
        var service = new TokenService(options);

        var result = service.Create(user, [SystemRoles.Teacher]);
        var token = new JwtSecurityTokenHandler().ReadJwtToken(result.Token);

        Assert.Contains(token.Claims, x =>
            x.Type == ClaimTypes.Role && x.Value == SystemRoles.Teacher);
        Assert.Contains(token.Claims, x =>
            x.Type == ClaimTypes.Name && x.Value == "陈老师");
        Assert.InRange(
            result.ExpiresAt,
            DateTime.UtcNow.AddMinutes(9),
            DateTime.UtcNow.AddMinutes(11));
    }
}
