namespace NeonSprawl.Server.Game.Skills;

/// <summary>Applies NEO-38 skill progression table DDL once per process.</summary>
public static class PostgresSkillProgressionBootstrap
{
    private static readonly string DdlRelativePath = Path.Combine("db", "migrations", "V003__player_skill_progression.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-38 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);
        }
    }
}
