#nullable enable
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using IGP.UnitySDK.Abstractions;
using Newtonsoft.Json;
using NUnit.Framework;
using UnityEngine;

namespace IGP.UnitySDK.GameKit.Tests
{
    public sealed class IGPFriendMonitorTests
    {
        private sealed class Source : IIGPHostServiceMessageSource
        {
            public event Action<IGPHostServiceMessage>? ServiceMessageReceived;
            public event Action? ServiceMessageStreamReset;
            internal void Receive(string json) => ServiceMessageReceived?.Invoke(new IGPHostServiceMessage(
                "message", IGPHostServiceMessageSubcommand.GameKitFriendsPresence, json));
            internal void Reset() => ServiceMessageStreamReset?.Invoke();
        }

        private static IGPDesktopSessionCommandResult Result(string id = "s") =>
            new IGPDesktopSessionCommandResult { Success = true, ContentJson = "{\"subscriptionId\":\"" + id + "\"}" };

        private static IGPFriendsException ExpectFailure(Task operation)
        {
            try { operation.GetAwaiter().GetResult(); }
            catch (IGPFriendsException exception) { return exception; }
            Assert.Fail("Expected a friends failure");
            return null!;
        }

        private static string Snapshot(long revision, string[]? online = null, string[]? desktop = null,
            string status = "ready", string id = "s") => JsonConvert.SerializeObject(new {
                schemaVersion = 1, subscriptionId = id, revision, status,
                onlineUserIds = online ?? Array.Empty<string>(), desktopOnlineUserIds = desktop ?? Array.Empty<string>() });

        private static IGPFriendMonitor Create(Source source, List<bool> commands, object? key = null,
            Func<bool, Task<IGPDesktopSessionCommandResult>>? send = null, CancellationToken lifetime = default) =>
            new IGPFriendMonitor(key ?? new object(), source,
                () => enabled => { commands.Add(enabled); return send?.Invoke(enabled) ?? Task.FromResult(Result()); }, () => lifetime);

        [Test]
        public void InitialBaseline_ContentDiff_Duplicates_AndDesktopOnlineAreIndependent()
        {
            var source = new Source(); var commands = new List<bool>();
            var monitor = Create(source, commands);
            var events = new List<IGPFriendStatusChanged>();
            monitor.FriendStatusChanged += change => {
                Assert.AreEqual(IGPFriendPresenceStatus.Ready, monitor.CurrentSnapshot!.Status);
                events.Add(change);
            };
            monitor.StartAsync().GetAwaiter().GetResult();
            source.Receive(Snapshot(1, new[] { "a" }));
            Assert.IsEmpty(events);
            source.Receive(Snapshot(2, new[] { "a" }));
            Assert.IsEmpty(events);
            source.Receive(Snapshot(3, new[] { "a" }, new[] { "a" }));
            Assert.AreEqual(1, events.Count);
            Assert.IsTrue(events[0].WasOnline); Assert.IsTrue(events[0].IsOnline);
            Assert.IsFalse(events[0].WasDesktopOnline); Assert.IsTrue(events[0].IsDesktopOnline);
            source.Receive(Snapshot(3)); // repeated/stale revision
            source.Receive(Snapshot(2));
            Assert.AreEqual(1, events.Count);
            source.Receive(Snapshot(4));
            Assert.AreEqual(2, events.Count); Assert.IsFalse(events[1].IsOnline);
            monitor.StopAsync().GetAwaiter().GetResult();
            Assert.IsNull(monitor.CurrentSnapshot);
            CollectionAssert.AreEqual(new[] { true, false }, commands);
        }

        [TestCase("error")]
        [TestCase("loading")]
        [TestCase("idle")]
        public void UnavailableAndRecoveryDoNotInventOfflineOrOnlineEvents(string status)
        {
            var source = new Source(); var monitor = Create(source, new List<bool>()); var count = 0;
            monitor.FriendStatusChanged += _ => count++;
            monitor.StartAsync().GetAwaiter().GetResult();
            source.Receive(Snapshot(1, new[] { "a" }));
            source.Receive(Snapshot(2, status: status));
            source.Receive(Snapshot(3, new[] { "b" }));
            Assert.AreEqual(0, count);
            source.Receive(Snapshot(4)); Assert.AreEqual(1, count);
            monitor.StopAsync().GetAwaiter().GetResult();
        }

        [Test]
        public void DuplicateStartAndStopAreIdempotent_OneMonitorPerRuntime_ResetReleasesOwnership()
        {
            var source = new Source(); var commands = new List<bool>(); var key = new object();
            var a = Create(source, commands, key); var b = Create(source, commands, key);
            a.StartAsync().GetAwaiter().GetResult(); a.StartAsync().GetAwaiter().GetResult();
            var error = ExpectFailure(b.StartAsync());
            Assert.AreEqual("FRIENDS_MONITOR_ALREADY_ACTIVE", error!.Code);
            CollectionAssert.AreEqual(new[] { true }, commands);
            source.Receive(Snapshot(1)); source.Reset();
            Assert.IsNull(a.CurrentSnapshot);
            a.StopAsync().GetAwaiter().GetResult();
            CollectionAssert.AreEqual(new[] { true }, commands); // no cleanup on a new session
            b.StartAsync().GetAwaiter().GetResult(); b.StopAsync().GetAwaiter().GetResult(); b.StopAsync().GetAwaiter().GetResult();
            CollectionAssert.AreEqual(new[] { true, true, false }, commands);
        }

        [Test]
        public void BuffersSnapshotsUntilCommandContinuation_AndIgnoresOldSubscriptionIds()
        {
            var source = new Source(); var commands = new List<bool>();
            var completion = new TaskCompletionSource<IGPDesktopSessionCommandResult>();
            var monitor = Create(source, commands, send: enabled => enabled ? completion.Task : Task.FromResult(Result()));
            var count = 0; monitor.FriendStatusChanged += _ => count++;
            var start = monitor.StartAsync();
            source.Receive(Snapshot(1, new[] { "a" }, id: "old"));
            source.Receive(Snapshot(1, new[] { "a" }));
            source.Receive(Snapshot(2));
            completion.SetResult(Result()); start.GetAwaiter().GetResult();
            Assert.AreEqual(1, count);
            source.Receive(Snapshot(9, new[] { "a" }, id: "old"));
            Assert.AreEqual(1, count);
            monitor.StopAsync().GetAwaiter().GetResult();
        }

        [Test]
        public void LifetimeEndAndResetDuringStartClearStateWithoutResubscribing()
        {
            var source = new Source(); var commands = new List<bool>();
            using var lifetime = new CancellationTokenSource();
            var monitor = Create(source, commands, lifetime: lifetime.Token);
            monitor.StartAsync().GetAwaiter().GetResult(); source.Receive(Snapshot(1)); lifetime.Cancel();
            Assert.IsNull(monitor.CurrentSnapshot);
            monitor.StopAsync().GetAwaiter().GetResult(); CollectionAssert.AreEqual(new[] { true }, commands);

            var pending = new TaskCompletionSource<IGPDesktopSessionCommandResult>();
            var other = Create(source, commands, send: _ => pending.Task);
            var start = other.StartAsync(); source.Reset(); pending.SetResult(Result());
            var error = ExpectFailure(start);
            Assert.AreEqual("FRIENDS_SESSION_ENDED", error!.Code);
            CollectionAssert.AreEqual(new[] { true, true }, commands);
        }

        [Test]
        public void InvalidPayloadAndSubscriberExceptionsNeverExposeBusinessData()
        {
            var source = new Source(); var monitor = Create(source, new List<bool>());
            var count = 0;
            monitor.FriendStatusChanged += _ => throw new Exception("private-subscriber-body");
            monitor.FriendStatusChanged += _ => count++;
            monitor.StartAsync().GetAwaiter().GetResult();
            source.Receive("{private-payload");
            source.Receive(Snapshot(1, new[] { "private-id", "private-id" }));
            Assert.IsNull(monitor.CurrentSnapshot);
            source.Receive(Snapshot(1, new[] { "private-id" }));
            source.Receive(Snapshot(2)); Assert.AreEqual(1, count);
            monitor.StopAsync().GetAwaiter().GetResult();
        }

        [Test]
        public void SnapshotsAreReadOnly_AndFailuresAreSanitizedWithLifecycleLogs()
        {
            var logs = new List<string>();
            Application.LogCallback capture = (message, trace, type) => logs.Add(message);
            Application.logMessageReceived += capture;
            IGPLog.Configure(IGPLogLevel.Info);
            var source = new Source(); var commands = new List<bool>();
            var monitor = Create(source, commands);
            try
            {
                monitor.StartAsync().GetAwaiter().GetResult();
                source.Receive(Snapshot(1, new[] { "private-id" }));
                Assert.Throws<NotSupportedException>(() => ((IList<string>)monitor.CurrentSnapshot!.OnlineUserIds)[0] = "changed");
                monitor.FriendStatusChanged += _ => throw new Exception("private-error");
                source.Receive(Snapshot(2));
                source.Receive("private-body");
                monitor.StopAsync().GetAwaiter().GetResult();
                var failed = Create(source, commands, send: enabled => enabled
                    ? Task.FromException<IGPDesktopSessionCommandResult>(new Exception("private-error"))
                    : Task.FromResult(Result()));
                var exception = ExpectFailure(failed.StartAsync());
                StringAssert.DoesNotContain("private", exception!.ToString());
                var text = string.Join("\n", logs);
                StringAssert.Contains("subscribe", text);
                StringAssert.Contains("result=start", text);
                StringAssert.Contains("result=complete", text);
                StringAssert.Contains("subscriber-failed", text);
                StringAssert.Contains("invalid-payload", text);
                StringAssert.DoesNotContain("private", text);
                StringAssert.DoesNotContain("onlineUserIds", text);
            }
            finally
            {
                monitor.StopAsync().GetAwaiter().GetResult();
                Application.logMessageReceived -= capture;
                IGPLog.Configure(IGPLogLevel.Off);
            }
        }

        [Test]
        public void PublicMonitorHasParameterlessLifecycleAndNoDtoConstructors()
        {
            Assert.IsEmpty(typeof(IGPFriendMonitor).GetMethod("StartAsync")!.GetParameters());
            Assert.IsEmpty(typeof(IGPFriendMonitor).GetMethod("StopAsync")!.GetParameters());
            Assert.IsEmpty(typeof(IGPFriendPresenceSnapshot).GetConstructors());
            Assert.IsEmpty(typeof(IGPFriendStatusChanged).GetConstructors());
        }

        [Test]
        public void CoreQueuesDeliveryUntilMainThreadUpdate()
        {
            var gameObject = new GameObject("friends-test");
            var runtime = gameObject.AddComponent<IGPRuntimeManager>();
            var flags = BindingFlags.NonPublic | BindingFlags.Instance;
            typeof(IGPRuntimeManager).GetField("sdkInitialized", flags)!.SetValue(runtime, true);
            var monitor = new IGPFriendMonitor(runtime, (IIGPHostServiceMessageSource)runtime,
                () => _ => Task.FromResult(Result()), () => CancellationToken.None);
            var mainThread = Thread.CurrentThread.ManagedThreadId;
            var eventThread = 0;
            monitor.FriendStatusChanged += _ => eventThread = Thread.CurrentThread.ManagedThreadId;
            try
            {
                monitor.StartAsync().GetAwaiter().GetResult();
                var receive = typeof(IGPRuntimeManager).GetMethod("HandleHostServiceMessageReceived", flags)!;
                var drain = typeof(IGPRuntimeManager).GetMethod("DrainHostServiceMessages", flags)!;
                Task.Run(() => receive.Invoke(runtime, new object[] { new IGPHostServiceMessage("1", IGPHostServiceMessageSubcommand.GameKitFriendsPresence, Snapshot(1)) })).GetAwaiter().GetResult();
                Assert.IsNull(monitor.CurrentSnapshot); drain.Invoke(runtime, null);
                receive.Invoke(runtime, new object[] { new IGPHostServiceMessage("2", IGPHostServiceMessageSubcommand.GameKitFriendsPresence, Snapshot(2, new[] { "a" })) });
                Assert.AreEqual(0, eventThread); drain.Invoke(runtime, null);
                Assert.AreEqual(mainThread, eventThread);
                monitor.StopAsync().GetAwaiter().GetResult();
            }
            finally { UnityEngine.Object.DestroyImmediate(gameObject); }
        }
    }
}
