using Eis.Infrastructure.Authentication;

namespace Eis.Infrastructure.Tests.Authentication;

public sealed class TotpCompatibilityServiceTests
{
    private const string EncryptionKey = "test-only-totp-encryption-key-32-characters";
    private readonly TotpCompatibilityService _service = new(AuthenticationOptions.CreateForTests(EncryptionKey));

    [Fact]
    public void MatchesRfc6238NodeVector()
    {
        Assert.Equal("287082", _service.AtStep("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", 1));
    }

    [Fact]
    public void DecryptsNodeAesGcmPayloadAndRoundTripsDotnetPayload()
    {
        const string nodePayload = "v1.BW3b8OSqNLprCfpr.UUw1AKfqGvmo11YQUhHuPQ.GbPra-HNEUS3uWPJqwVpw2utLYbs89rlPOwhuNl7QYk";
        const string secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";

        Assert.Equal(secret, _service.DecryptSecret(nodePayload));
        Assert.Equal(secret, _service.DecryptSecret(_service.EncryptSecret(secret)));
    }

    [Fact]
    public void MatchesNodeRecoveryHashAndOtpAuthUri()
    {
        Assert.Equal(
            "662bf005217b529934526e0c8755c0c48d4dab012dfe96191080a6675334559c",
            _service.HashRecoveryCode("ABCDE-23456"));
        Assert.Equal(
            "otpauth://totp/%E6%B5%B7%E5%B7%9E%20%E8%80%83%E8%AF%95%E4%B8%AD%E5%BF%83%3A2026%200001?secret=ABCDEF234567&issuer=%E6%B5%B7%E5%B7%9E+%E8%80%83%E8%AF%95%E4%B8%AD%E5%BF%83&algorithm=SHA1&digits=6&period=30",
            _service.BuildOtpAuthUri("ABCDEF234567", "2026 0001", "海州 考试中心"));
    }

    [Fact]
    public void RecoveryCodeCanOnlyBeConsumedOnce()
    {
        var hashes = new[] { _service.HashRecoveryCode("ABCDE-23456"), _service.HashRecoveryCode("FGHJK-78923") };
        var remaining = _service.ConsumeRecoveryCode("abcde 23456", hashes);

        Assert.NotNull(remaining);
        Assert.Single(remaining);
        Assert.Null(_service.ConsumeRecoveryCode("ABCDE-23456", remaining));
    }
}
