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

namespace CounterDrone.Core.Tests
{
    public class RepositoryEdgeTests : IDisposable
    {
        private readonly string _testDir;
        private readonly SQLite.SQLiteConnection _db;

        public RepositoryEdgeTests()
        {
            _testDir = Path.Combine(Path.GetTempPath(), $"cd_repo_{Guid.NewGuid():N}");
            var paths = new TestPathProvider(_testDir);
            _db = new DatabaseManager(paths).OpenMainDb();
        }

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

        [Fact]
        public void TargetConfig_DeleteByTaskId_RemovesAll()
        {
            var repo = new TargetConfigRepository(_db);
            repo.Insert(new TargetConfig { Id = "t1", TaskId = "taskA", Quantity = 1 });
            repo.Insert(new TargetConfig { Id = "t2", TaskId = "taskA", Quantity = 2 });
            repo.Insert(new TargetConfig { Id = "t3", TaskId = "taskB", Quantity = 1 });

            repo.DeleteByTaskId("taskA");

            Assert.Empty(repo.GetByTaskId("taskA"));
            Assert.Single(repo.GetByTaskId("taskB"));
        }

        [Fact]
        public void Waypoint_DeleteByTaskId_RemovesAll()
        {
            var repo = new WaypointRepository(_db);
            repo.Insert(new Waypoint { TaskId = "w1", OrderIndex = 0 });
            repo.Insert(new Waypoint { TaskId = "w1", OrderIndex = 1 });
            repo.Insert(new Waypoint { TaskId = "w2", OrderIndex = 0 });

            repo.DeleteByTaskId("w1");

            Assert.Empty(repo.GetByTaskId("w1"));
            Assert.Single(repo.GetByTaskId("w2"));
        }

        [Fact]
        public void EquipmentDeployment_DeleteByTaskId_Works()
        {
            var repo = new EquipmentDeploymentRepository(_db);
            repo.Insert(new EquipmentDeployment { Id = "e1", TaskId = "eqA" });
            repo.Insert(new EquipmentDeployment { Id = "e2", TaskId = "eqA" });

            repo.DeleteByTaskId("eqA");
            Assert.Empty(repo.GetByTaskId("eqA"));
        }
    }
}
