using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;

namespace NeonSprawl.Server.Tests.Game.PositionState;

/// <summary>Integration host with <see cref="PositionStateServiceCollectionExtensions.NeonSprawlConnectionStringName"/> bound from environment.</summary>
public sealed class PostgresWebApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        var cs = Environment.GetEnvironmentVariable("ConnectionStrings__NeonSprawl");
        PostgresDockerHelper.EnsurePostgresOrStartDockerBlocking(cs);
        if (string.IsNullOrWhiteSpace(cs))
        {
            throw new InvalidOperationException(
                "Set ConnectionStrings__NeonSprawl for Postgres integration tests (see server/README.md).");
        }

        builder.ConfigureAppConfiguration((_, config) =>
        {
            config.AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["ConnectionStrings:NeonSprawl"] = cs.Trim(),
            });
        });
    }
}
