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 ScenarioDrone_DeleteByScenarioId_RemovesAll()
        {
            var repo = new ScenarioDroneRepository(_db);
            repo.Insert(TestData.CreateScenarioDroneWithId("scenarioA", "w1"));
            repo.Insert(TestData.CreateScenarioDroneWithId("scenarioA", "w2"));
            repo.Insert(TestData.CreateScenarioDroneWithId("scenarioA", "w3"));
            repo.Insert(TestData.CreateScenarioDroneWithId("scenarioB", "w4"));

            repo.DeleteByScenarioId("scenarioA");

            Assert.Empty(repo.GetByScenarioId("scenarioA"));
            Assert.Single(repo.GetByScenarioId("scenarioB"));
        }

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

            repo.DeleteByScenarioId("w1");

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

        [Fact]
        public void ScenarioUnit_DeleteByScenarioId_Works()
        {
            var repo = new ScenarioUnitRepository(_db);
            repo.Insert(TestData.CreateScenarioUnit(0, 0, 50, 0, null));
            repo.Insert(TestData.CreateScenarioUnit(0, 0, 50, 0, null));

            repo.DeleteByScenarioId("eqA");
            Assert.Empty(repo.GetByScenarioId("eqA"));
        }
    }
}
