namespace NeonSprawl.Server.Game.PositionState;

/// <summary>Registers position authority: PostgreSQL when <c>ConnectionStrings:NeonSprawl</c> is set, otherwise in-memory (NS-15 / NS-17).</summary>
public static class PositionStateServiceCollectionExtensions
{
    internal const string NeonSprawlConnectionStringName = "NeonSprawl";

    public static IServiceCollection AddPositionStateStore(this IServiceCollection services, IConfiguration configuration)
    {
        services.Configure<GamePositionOptions>(configuration.GetSection(GamePositionOptions.SectionName));

        var cs = configuration.GetConnectionString(NeonSprawlConnectionStringName);
        if (!string.IsNullOrWhiteSpace(cs))
        {
            var trimmed = cs.Trim();
            services.AddSingleton<Npgsql.NpgsqlDataSource>(_ => Npgsql.NpgsqlDataSource.Create(trimmed));
            services.AddHostedService<NpgsqlDataSourceShutdownHostedService>();
            services.AddHostedService<PostgresDevPlayerSeedHostedService>();
            services.AddSingleton<IPositionStateStore, PostgresPositionStateStore>();
        }
        else
        {
            services.AddSingleton<IPositionStateStore, InMemoryPositionStateStore>();
        }

        return services;
    }
}
