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

namespace CounterDrone.Core.Tests
{
    public class DatabaseManagerTests : IDisposable
    {
        private readonly string _testDir;
        private readonly IPathProvider _paths;
        private readonly DatabaseManager _dbManager;

        public DatabaseManagerTests()
        {
            _testDir = Path.Combine(Path.GetTempPath(), $"cd_test_{Guid.NewGuid():N}");
            _paths = new TestPathProvider(_testDir);
            _dbManager = new DatabaseManager(_paths);
        }

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

        [Fact]
        public void OpenMainDb_CreatesAllTables()
        {
            var db = _dbManager.OpenMainDb();

            // 验证所有 12 张表存在
            var tables = new[]
            {
                "ModelInfo", "AmmunitionSpec", "SimTask", "CombatScene",
                "ControlZone", "TargetConfig", "EquipmentDeployment",
                "CloudDispersal", "RoutePlan", "Waypoint", "Group",
                "SimulationReport"
            };

            foreach (var table in tables)
            {
                var count = db.ExecuteScalar<int>(
                    $"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='{table}'");
                Assert.Equal(1, count);
            }

            db.Close();
        }

        [Fact]
        public void OpenFrameDb_CreatesFrameRecordTable()
        {
            var db = _dbManager.OpenFrameDb("task_001");

            var count = db.ExecuteScalar<int>(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='SimFrameRecord'");
            Assert.Equal(1, count);

            db.Close();
        }

        [Fact]
        public void DeleteFrameDb_RemovesFile()
        {
            var taskId = "task_del";
            var db = _dbManager.OpenFrameDb(taskId);
            db.Close();

            _dbManager.DeleteFrameDb(taskId);

            var dbPath = Path.Combine(_paths.GetFramesDir(), $"{taskId}.db");
            Assert.False(File.Exists(dbPath));
        }

        [Fact]
        public void OpenMainDb_IsIdempotent()
        {
            var db1 = _dbManager.OpenMainDb();
            db1.Close();

            // 第二次打开不抛异常
            var db2 = _dbManager.OpenMainDb();
            db2.Close();
        }
    }
}
