using System;
using System.IO;
using CounterDrone.Core;
using CounterDrone.Core.Models;
using CounterDrone.Core.Repository;
using SQLite;
using Xunit;

namespace CounterDrone.Core.Tests
{
    public class GroupRepositoryTests : IDisposable
    {
        private readonly string _testDir;
        private readonly SQLiteConnection _db;
        private readonly GroupRepository _repo;

        public GroupRepositoryTests()
        {
            _testDir = Path.Combine(Path.GetTempPath(), $"cd_test_{Guid.NewGuid():N}");
            var paths = new TestPathProvider(_testDir);
            var dbManager = new DatabaseManager(paths);
            _db = dbManager.OpenMainDb();
            _repo = new GroupRepository(_db);
        }

        public void Dispose()
        {
            _db?.Close();
            if (Directory.Exists(_testDir))
                Directory.Delete(_testDir, true);
        }

        [Fact]
        public void Insert_And_GetById_ReturnsGroup()
        {
            var group = new Group
            {
                Name = "Alpha Fleet",
                GroupType = (int)GroupType.DroneFleet,
                Description = "Test drone formation"
            };

            _repo.Insert(group);

            var result = _repo.GetById(group.Id);
            Assert.NotNull(result);
            Assert.Equal("Alpha Fleet", result.Name);
            Assert.Equal((int)GroupType.DroneFleet, result.GroupType);
        }

        [Fact]
        public void GetByType_FiltersCorrectly()
        {
            _repo.Insert(new Group { Name = "Fleet A", GroupType = (int)GroupType.DroneFleet });
            _repo.Insert(new Group { Name = "Fleet B", GroupType = (int)GroupType.DroneFleet });
            _repo.Insert(new Group { Name = "Equip G1", GroupType = (int)GroupType.EquipmentGroup });

            var fleets = _repo.GetByType((int)GroupType.DroneFleet);
            Assert.Equal(2, fleets.Count);

            var equipGroups = _repo.GetByType((int)GroupType.EquipmentGroup);
            Assert.Single(equipGroups);
        }

        [Fact]
        public void Delete_RemovesGroup()
        {
            var group = new Group { Name = "ToDelete" };
            _repo.Insert(group);
            _repo.Delete(group.Id);

            Assert.Null(_repo.GetById(group.Id));
        }
    }
}
