using System.Collections.Generic;
using SQLite;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace CounterDrone.Unity
{
    /// <summary>追踪所有打开的 SQLite 连接，在 domain reload 前安全关闭</summary>
    public static class SqliteConnectionTracker
    {
        private static readonly List<SQLiteConnection> _connections = new();

        static SqliteConnectionTracker()
        {
#if UNITY_EDITOR
            AssemblyReloadEvents.beforeAssemblyReload += DisposeAll;
#endif
        }

        public static void Track(SQLiteConnection db)
        {
            lock (_connections) { _connections.Add(db); }
        }

        public static void Untrack(SQLiteConnection db)
        {
            lock (_connections) { _connections.Remove(db); }
        }

        private static void DisposeAll()
        {
            lock (_connections)
            {
                foreach (var db in _connections)
                {
                    try { db.Dispose(); }
                    catch { /* absorb */ }
                }
                _connections.Clear();
            }
        }
    }
}
