using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;

namespace NavisworksTransport.UnitTests.Integration
{
    /// <summary>
    /// 检测记录持久化集成测试（覆盖计划 T10）。
    ///
    /// 验证碰撞检测记录正确落库并可查询：
    /// - 动画产生的检测记录 ID 有效
    /// - 从数据库重新加载后：关联路径、动画参数（帧率/时长）、虚拟物体模式、物体名一致
    ///
    /// 动画参数（15fps/5s）与测试执行参数一致，验证参数链完整贯穿到持久化层。
    /// </summary>
    [TestClass]
    [TestCategory("NavisworksIntegration")]
    public class DetectionRecordPersistenceAutomationTests
    {
        private const int TestFrameRate = 15;
        private const double TestDurationSeconds = 5.0;

        [TestMethod]
        [Timeout(240000)]
        public async Task DetectionRecord_GeneratedByAnimation_PersistedAndReloadable()
        {
            using (var client = new NavisworksTestAutomationClient())
            {
                await client.EnsureServiceReadyAsync(TimeSpan.FromSeconds(90)).ConfigureAwait(false);

                // 1. 生成一次 Ground 虚拟物体动画（15fps/5s）
                JObject animationResponse = await client.RunCollisionTestAsync(
                    "Ground",
                    240,
                    frameRate: TestFrameRate,
                    durationSeconds: TestDurationSeconds).ConfigureAwait(false);
                Assert.IsTrue(animationResponse.Value<bool>("ok"), "碰撞测试失败: " + (string)animationResponse["error"]);

                JObject data = (JObject)animationResponse["data"];
                JObject route = (JObject)data["route"];
                int detectionRecordId = (int)data["animation"]["detectionRecordId"];
                Assert.IsTrue(detectionRecordId > 0, "检测记录 ID 无效");

                // 2. 从数据库重新加载检测记录
                JObject recordResponse = await client.GetDetectionRecordAsync(detectionRecordId).ConfigureAwait(false);
                Assert.IsTrue(recordResponse.Value<bool>("ok"), "查询检测记录失败: " + (string)recordResponse["error"]);

                JObject record = (JObject)recordResponse["data"];

                // 记录 ID 匹配
                Assert.AreEqual(detectionRecordId, (int)record["id"], "检测记录 ID 不匹配");

                // 关联路径
                Assert.AreEqual((string)route["id"], (string)record["routeId"], "检测记录关联路径 ID 不匹配");
                Assert.IsFalse(string.IsNullOrWhiteSpace((string)record["testName"]), "检测记录测试名为空");

                // 动画参数持久化（与测试执行参数一致）
                Assert.AreEqual(TestFrameRate, (int)record["frameRate"], "检测记录帧率不匹配");
                Assert.AreEqual(TestDurationSeconds, (double)record["durationSeconds"], 1e-6, "检测记录时长不匹配");

                // 虚拟物体模式与物体信息
                Assert.IsTrue((bool)record["isVirtualObject"], "检测记录应标记为虚拟物体模式");
                Assert.IsFalse(string.IsNullOrWhiteSpace((string)record["animatedObjectName"]), "检测记录缺少物体名");

                // 碰撞计数非负
                Assert.IsTrue((int)record["collisionCount"] >= 0, "碰撞计数不能为负");
            }
        }
    }
}
