using NATS.Server.Auth.Jwt;

namespace NATS.Server.Tests;

public class AccountResolverTests
{
    [Fact]
    public async Task Store_and_fetch_roundtrip()
    {
        var resolver = new MemAccountResolver();
        const string nkey = "AABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQ";
        const string jwt = "eyJhbGciOiJlZDI1NTE5LW5rZXkiLCJ0eXAiOiJKV1QifQ.payload.sig";

        await resolver.StoreAsync(nkey, jwt);
        var fetched = await resolver.FetchAsync(nkey);

        fetched.ShouldBe(jwt);
    }

    [Fact]
    public async Task Fetch_unknown_key_returns_null()
    {
        var resolver = new MemAccountResolver();

        var result = await resolver.FetchAsync("UNKNOWN_NKEY");

        result.ShouldBeNull();
    }

    [Fact]
    public async Task Store_overwrites_existing_entry()
    {
        var resolver = new MemAccountResolver();
        const string nkey = "AABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQ";
        const string originalJwt = "original.jwt.token";
        const string updatedJwt = "updated.jwt.token";

        await resolver.StoreAsync(nkey, originalJwt);
        await resolver.StoreAsync(nkey, updatedJwt);
        var fetched = await resolver.FetchAsync(nkey);

        fetched.ShouldBe(updatedJwt);
    }

    [Fact]
    public void IsReadOnly_returns_false()
    {
        IAccountResolver resolver = new MemAccountResolver();

        resolver.IsReadOnly.ShouldBeFalse();
    }

    [Fact]
    public async Task Multiple_accounts_are_stored_independently()
    {
        var resolver = new MemAccountResolver();
        const string nkey1 = "AABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQ1";
        const string nkey2 = "AABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQ2";
        const string jwt1 = "jwt.for.account.one";
        const string jwt2 = "jwt.for.account.two";

        await resolver.StoreAsync(nkey1, jwt1);
        await resolver.StoreAsync(nkey2, jwt2);

        (await resolver.FetchAsync(nkey1)).ShouldBe(jwt1);
        (await resolver.FetchAsync(nkey2)).ShouldBe(jwt2);
    }
}
