namespace NeonSprawl.Server.Game.AbilityInput;

/// <summary>Applies NEO-29 hotbar loadout table DDL once per process.</summary>
public static class PostgresHotbarLoadoutBootstrap
{
    private static readonly string DdlRelativePath = Path.Combine("db", "migrations", "V002__player_hotbar_loadout.sql");
    private static readonly object SchemaGate = new();
    private static int _schemaReady;

    public static void EnsureSchema(Npgsql.NpgsqlDataSource dataSource)
    {
        if (System.Threading.Volatile.Read(ref _schemaReady) != 0)
        {
            return;
        }

        lock (SchemaGate)
        {
            if (System.Threading.Volatile.Read(ref _schemaReady) != 0)
            {
                return;
            }

            var ddlPath = Path.Combine(AppContext.BaseDirectory, DdlRelativePath);
            if (!File.Exists(ddlPath))
            {
                throw new FileNotFoundException($"NEO-29 DDL not found at '{ddlPath}'.", ddlPath);
            }

            var ddl = File.ReadAllText(ddlPath);
            using var conn = dataSource.OpenConnection();
            using var cmd = new Npgsql.NpgsqlCommand(ddl, conn);
            cmd.ExecuteNonQuery();
            System.Threading.Volatile.Write(ref _schemaReady, 1);
        }
    }
}
