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

namespace CounterDrone.Core.Tests
{
    public class GroupServiceTests : IDisposable
    {
        private readonly string _testDir;
        private readonly SQLiteConnection _db;
        private readonly IGroupService _service;

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

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

        [Fact]
        public void CreateGroup_Valid_ReturnsGroup()
        {
            var group = _service.CreateGroup("Alpha", GroupType.DroneFleet, "Test fleet");

            Assert.NotNull(group);
            Assert.Equal("Alpha", group.Name);
            Assert.NotEmpty(group.Id);
        }

        [Fact]
        public void CreateGroup_EmptyName_Throws()
        {
            Assert.Throws<ArgumentException>(() =>
                _service.CreateGroup("", GroupType.DroneFleet, ""));
        }

        [Fact]
        public void GetGroups_WithTypeFilter()
        {
            _service.CreateGroup("Fleet A", GroupType.DroneFleet, "");
            _service.CreateGroup("Fleet B", GroupType.DroneFleet, "");
            _service.CreateGroup("Equip X", GroupType.EquipmentGroup, "");

            var fleets = _service.GetGroups(GroupType.DroneFleet);
            Assert.Equal(2, fleets.Count);

            var all = _service.GetGroups(null);
            Assert.Equal(3, all.Count);
        }

        [Fact]
        public void DeleteGroup_RemovesGroup()
        {
            var group = _service.CreateGroup("DeleteMe", GroupType.DroneFleet, "");
            _service.DeleteGroup(group.Id);

            Assert.Null(_service.GetGroup(group.Id));
        }

        [Fact]
        public void GetGroup_ById_ReturnsCorrectGroup()
        {
            var created = _service.CreateGroup("Target", GroupType.EquipmentGroup, "desc");
            var fetched = _service.GetGroup(created.Id);

            Assert.Equal("Target", fetched.Name);
            Assert.Equal("desc", fetched.Description);
        }
    }
}
