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 ModelRepositoryTests : IDisposable
    {
        private readonly string _testDir;
        private readonly SQLiteConnection _db;
        private readonly ModelRepository _repo;

        public ModelRepositoryTests()
        {
            _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 ModelRepository(_db);
        }

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

        [Fact]
        public void Insert_And_GetById_ReturnsModel()
        {
            var model = new ModelInfo
            {
                Name = "Test Drone",
                FilePath = "/models/drone.fbx",
                FileSize = 2.5
            };

            _repo.Insert(model);

            var result = _repo.GetById(model.Id);
            Assert.NotNull(result);
            Assert.Equal("Test Drone", result.Name);
            Assert.Equal(2.5, result.FileSize);
        }

        [Fact]
        public void GetAll_ReturnsAllModels()
        {
            _repo.Insert(new ModelInfo { Name = "A" });
            _repo.Insert(new ModelInfo { Name = "B" });
            _repo.Insert(new ModelInfo { Name = "C" });

            var all = _repo.GetAll();
            Assert.Equal(3, all.Count);
        }

        [Fact]
        public void Delete_RemovesModel()
        {
            var model = new ModelInfo { Name = "ToDelete" };
            _repo.Insert(model);

            _repo.Delete(model.Id);

            var result = _repo.GetById(model.Id);
            Assert.Null(result);
        }

        [Fact]
        public void Update_ModifiesModel()
        {
            var model = new ModelInfo { Name = "Original" };
            _repo.Insert(model);

            model.Name = "Updated";
            _repo.Update(model);

            var result = _repo.GetById(model.Id);
            Assert.Equal("Updated", result.Name);
        }

        [Fact]
        public void GetById_NonExistent_ReturnsNull()
        {
            var result = _repo.GetById("nonexistent");
            Assert.Null(result);
        }
    }
}
