using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NeonSprawl.Server.Game.AbilityInput;
using NeonSprawl.Server.Game.PositionState;
using Npgsql;

namespace NeonSprawl.Server.Tests;

/// <summary>Forces the in-memory position store by replacing Postgres registrations after the host builds services (overrides process env e.g. CI <c>ConnectionStrings__NeonSprawl</c>).</summary>
public sealed class InMemoryWebApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =>
        {
            for (var i = services.Count - 1; i >= 0; i--)
            {
                var d = services[i];
                if (d.ServiceType == typeof(IPositionStateStore) ||
                    d.ServiceType == typeof(IPlayerHotbarLoadoutStore) ||
                    d.ServiceType == typeof(NpgsqlDataSource) ||
                    (d.ServiceType == typeof(IHostedService) &&
                     (d.ImplementationType == typeof(PostgresDevPlayerSeedHostedService) ||
                      d.ImplementationType == typeof(NpgsqlDataSourceShutdownHostedService))))
                {
                    services.RemoveAt(i);
                }
            }

            services.AddSingleton<IPositionStateStore, InMemoryPositionStateStore>();
            services.AddSingleton<IPlayerHotbarLoadoutStore, InMemoryPlayerHotbarLoadoutStore>();
        });
    }
}
