namespace NeonSprawl.Server.Game.Mastery;

/// <summary>Applies NEO-47 perk state table DDL once per process.</summary>
public static class PostgresPerkStateBootstrap
{
    private static readonly string DdlRelativePath = Path.Combine("db", "migrations", "V004__player_perk_state.sql");

    private static readonly object SchemaGate = new();

    private static int _schemaReady;

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

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

            var ddlPath = Path.Combine(AppContext.BaseDirectory, DdlRelativePath);
            if (!File.Exists(ddlPath))
            {
                throw new FileNotFoundException($"NEO-47 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();
            Volatile.Write(ref _schemaReady, 1);
        }
    }
}
