using System.Collections.Generic;
using CounterDrone.Core;
using CounterDrone.Core.Models;
using CounterDrone.Core.Repository;
using CounterDrone.Core.Services;
using UnityEngine;

namespace CounterDrone.Unity
{
    /// <summary>编组管理桥接 — 无人机编队和装备编组的 CRUD</summary>
    public class GroupManager : MonoBehaviour
    {
        private IGroupService _service;
        private SQLite.SQLiteConnection _db;

        public IGroupService Service => _service;

        public void Awake()
        {
            var paths = new UnityPathProvider();
            _db = new DatabaseManager(paths).OpenMainDb();
            SqliteConnectionTracker.Track(_db);
            _service = new GroupService(new GroupRepository(_db));
        }

        void OnDisable() { SqliteConnectionTracker.Untrack(_db); _db?.Dispose(); _db = null; }

        public Group Create(string name, GroupType type, string desc = "")
            => _service.CreateGroup(name, type, desc);

        public void Delete(string id) => _service.DeleteGroup(id);

        public List<Group> GetByType(GroupType? type = null) => _service.GetGroups(type);

        public Group Get(string id) => _service.GetGroup(id);

        [ContextMenu("Verify")]
        void Verify()
        {
            Awake();
            var g = Create("测试编队", GroupType.DroneFleet, "自动验证");
            Debug.Log($"GroupManager OK. Created: {g.Name} ({g.Id})");
        }
    }
}
