using GameList.Domain;
using GameList.Infrastructure;
using GameList.Tests.Support;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace GameList.Tests;

public class IdentityTests
{
    [Fact]
    public async Task Sign_in_sets_claims_and_cookie()
    {
        await using var factory = new TestWebApplicationFactory();
        var ctx = BuildAuthContext();

        var player = new Player
        {
            Id = Guid.NewGuid(),
            Username = "claimuser",
            NormalizedUsername = "claimuser",
            PasswordHash = [1],
            PasswordSalt = [1],
            DisplayName = "Claim",
            IsAdmin = true
        };

        await PlayerIdentityExtensions.SignInPlayerAsync(ctx, player);

        var cookies = ctx.Response.Headers["Set-Cookie"];
        Assert.Contains(cookies, v => v != null && v.Contains(PlayerIdentityExtensions.PlayerCookieName));
    }

    [Fact]
    public async Task Sign_out_clears_principal()
    {
        await using var factory = new TestWebApplicationFactory();
        var ctx = BuildAuthContext();
        var player = new Player();
        await PlayerIdentityExtensions.SignInPlayerAsync(ctx, player);

        await PlayerIdentityExtensions.SignOutPlayerAsync(ctx);

        Assert.False(ctx.User.Identity?.IsAuthenticated ?? false);
    }

    private static DefaultHttpContext BuildAuthContext()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        serviceCollection.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => { options.Cookie.Name = PlayerIdentityExtensions.PlayerCookieName; });
        serviceCollection.AddLogging();
        var provider = serviceCollection.BuildServiceProvider();

        return new DefaultHttpContext
        {
            RequestServices = provider,
            Response = { Body = new MemoryStream() }
        };
    }
}
