#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using IGP.UnitySDK.Models;
using NUnit.Framework;
using UnityEngine;

namespace IGP.UnitySDK.GameKit.Tests
{
    public sealed class IGPFriendsTests
    {
        private const string FriendJson = "{\"profile\":{\"id\":\"friend-1\",\"nickname\":\"private-name\",\"avatarUrl\":null,\"avatarFrameUrl\":null},\"onlineStatus\":\"online\"}";

        [Test]
        public void PublicSurface_MatchesApprovedContract()
        {
            var declared = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static;
            CollectionAssert.AreEquivalent(new[] { "GetFriendsAsync", "SendFriendRequestAsync", "GetIncomingFriendRequestsAsync", "AcceptFriendRequestAsync" }, typeof(IGPFriends).GetMethods(declared).Select(m => m.Name).ToArray());
            foreach (var name in new[] { "SendFriendRequestAsync", "AcceptFriendRequestAsync" })
            {
                var action = typeof(IGPFriends).GetMethod(name)!;
                Assert.AreEqual(typeof(Task<IGPFriendRequestActionResult>), action.ReturnType);
                CollectionAssert.AreEqual(new[] { typeof(IGPRuntimeManager), typeof(string), typeof(CancellationToken) }, action.GetParameters().Select(p => p.ParameterType));
                Assert.IsTrue(action.GetParameters()[2].HasDefaultValue);
            }
            var incoming = typeof(IGPFriends).GetMethod("GetIncomingFriendRequestsAsync")!;
            Assert.AreEqual(typeof(Task<IGPIncomingFriendRequest[]>), incoming.ReturnType);
            CollectionAssert.AreEqual(new[] { typeof(IGPRuntimeManager), typeof(CancellationToken) }, incoming.GetParameters().Select(p => p.ParameterType));
            CollectionAssert.AreEquivalent(new[] { "friendshipId", "profile", "note", "requestedAt" }, typeof(IGPIncomingFriendRequest).GetFields(declared).Select(f => f.Name));
            CollectionAssert.AreEqual(new[] { "result" }, typeof(IGPFriendRequestActionResult).GetFields(declared).Select(f => f.Name));
            var method = typeof(IGPFriends).GetMethod("GetFriendsAsync")!;
            Assert.AreEqual(typeof(Task<IGPFriend[]>), method.ReturnType);
            Assert.AreEqual(new[] { typeof(IGPRuntimeManager) }, method.GetParameters().Select(p => p.ParameterType).ToArray());
            Assert.IsTrue(typeof(IGPFriend).IsSealed && typeof(IGPFriend).IsSerializable);
            CollectionAssert.AreEquivalent(new[] { "profile", "onlineStatus" }, typeof(IGPFriend).GetFields(declared).Select(f => f.Name));
            Assert.AreEqual(typeof(IGPPlayerProfile), typeof(IGPFriend).GetField("profile")!.FieldType);
            Assert.AreEqual(typeof(IGPFriendOnlineStatus), typeof(IGPFriend).GetField("onlineStatus")!.FieldType);
            CollectionAssert.AreEqual(new[] { "Offline", "Online" }, Enum.GetNames(typeof(IGPFriendOnlineStatus)));
            Assert.AreEqual(0, (int)IGPFriendOnlineStatus.Offline);
            Assert.AreEqual(1, (int)IGPFriendOnlineStatus.Online);
            Assert.AreEqual(new[] { "Code" }, typeof(IGPFriendsException).GetProperties(declared).Select(p => p.Name).ToArray());
            Assert.IsNull(typeof(IGPFriendsException).GetProperty("Code")!.GetSetMethod());
            Assert.AreEqual(typeof(Exception), typeof(IGPFriendsException).BaseType);
            Assert.IsTrue(typeof(IGPFriendsException).IsSealed);
            Assert.AreEqual(1, typeof(IGPFriendsException).GetConstructors().Length);
            Assert.IsNotNull(typeof(IGPFriendsException).GetConstructor(new[] { typeof(string), typeof(string) }));
            Assert.IsNull(typeof(IGPRuntimeManager).GetMethod("GetDesktopFriendsAsync", BindingFlags.Public | BindingFlags.Instance));
        }

        [Test]
        public void Query_ReturnsFreshSnapshotsAndEmptyList()
        {
            var calls = 0;
            Func<Task<IGPDesktopSessionCommandResult>> send = () =>
            {
                calls++;
                return Task.FromResult(new IGPDesktopSessionCommandResult { Success = true, ContentJson = "[" + FriendJson + "]" });
            };
            var first = IGPFriends.QueryAsync(send).GetAwaiter().GetResult();
            first[0].profile.id = "changed";
            var second = IGPFriends.QueryAsync(send).GetAwaiter().GetResult();
            Assert.AreEqual(2, calls);
            Assert.AreEqual("friend-1", second[0].profile.id);
            Assert.AreEqual(IGPFriendOnlineStatus.Online, second[0].onlineStatus);
            Assert.IsNull(second[0].profile.avatarUrl);
            Assert.AreEqual(0, IGPFriends.ParseResponse("[]").Length);
            Assert.AreEqual(IGPFriendOnlineStatus.Offline, IGPFriends.ParseResponse("[" + FriendJson.Replace("online\"}", "offline\"}") + "]")[0].onlineStatus);
        }

        [TestCase("REQUEST_SENT")]
        [TestCase("REQUEST_RESENT")]
        [TestCase("AUTO_ACCEPTED")]
        [TestCase("ACCEPTED")]
        public void Actions_PreserveHostOutcome(string outcome)
        {
            Assert.AreEqual(outcome, IGPFriends.ParseActionResponse("{\"result\":\"" + outcome + "\"}").result);
        }

        [Test]
        public void Incoming_ReturnsRelationshipIdAndFreshSnapshot()
        {
            var json = "[{\"friendshipId\":\"relation-1\",\"profile\":{\"id\":\"sender-1\",\"nickname\":null,\"avatarUrl\":null,\"avatarFrameUrl\":null},\"note\":\"private note\",\"requestedAt\":null}]";
            var first = IGPFriends.ParseIncomingResponse(json);
            Assert.AreEqual("relation-1", first[0].friendshipId);
            Assert.AreEqual("sender-1", first[0].profile.id);
            Assert.AreEqual("private note", first[0].note);
            first[0].profile.id = "changed";
            Assert.AreEqual("sender-1", IGPFriends.ParseIncomingResponse(json)[0].profile.id);
            Assert.IsEmpty(IGPFriends.ParseIncomingResponse("[]"));
        }

        [TestCase("null")]
        [TestCase("{}")]
        [TestCase("[null]")]
        [TestCase("private malformed body")]
        public void NewResponseFailures_AreSafe(string json)
        {
            Assert.AreEqual("FRIENDS_INVALID_RESPONSE", Assert.Throws<IGPFriendsException>(() => IGPFriends.ParseIncomingResponse(json))!.Code);
            Assert.AreEqual("FRIENDS_INVALID_RESPONSE", Assert.Throws<IGPFriendsException>(() => IGPFriends.ParseActionResponse(json))!.Code);
        }

        [Test]
        public void RequestRouting_PreservesErrorsAndCancellationWithoutSending()
        {
            var error = Assert.Throws<IGPFriendsException>(() => IGPFriends.ExecuteAsync("send-request", () =>
                Task.FromResult(new IGPDesktopSessionCommandResult { Success = false, Code = "UNSUPPORTED_COMMAND", Message = "private body" }),
                IGPFriends.ParseActionResponse).GetAwaiter().GetResult())!;
            Assert.AreEqual("UNSUPPORTED_COMMAND", error.Code);
            StringAssert.DoesNotContain("private", error.ToString());
            var calls = 0;
            Assert.Throws<OperationCanceledException>(() => IGPFriends.ExecuteAsync("get-incoming", () =>
            {
                calls++;
                return Task.FromResult(new IGPDesktopSessionCommandResult());
            }, IGPFriends.ParseIncomingResponse, new CancellationToken(true)).GetAwaiter().GetResult());
            Assert.AreEqual(0, calls);
        }

        [TestCase("null")]
        [TestCase("{}")]
        [TestCase("private-body invalid json")]
        [TestCase("[null]")]
        [TestCase("[{\"profile\":null,\"onlineStatus\":\"offline\"}]")]
        public void InvalidResponse_IsSafe(string json)
        {
            var error = Assert.Throws<IGPFriendsException>(() => IGPFriends.ParseResponse(json))!;
            Assert.AreEqual("FRIENDS_INVALID_RESPONSE", error.Code);
            Assert.AreEqual("Desktop friends response is invalid", error.Message);
            Assert.IsNull(error.InnerException);
        }

        [TestCase("\"unknown\"")]
        [TestCase("\"Online\"")]
        [TestCase("1")]
        [TestCase("null")]
        public void InvalidStatus_IsNotConvertedToOffline(string status)
        {
            InvalidResponse_IsSafe("[" + FriendJson.Replace("\"online\"", status) + "]");
        }

        [TestCase("ERR_DESKTOP_SESSION_REQUIRED")]
        [TestCase("ERR_HOST_USER_CONTEXT_REQUIRED")]
        [TestCase("UNSUPPORTED_COMMAND")]
        public void CommandFailures_PreserveCodeWithoutBody(string code)
        {
            var error = Assert.Throws<IGPFriendsException>(() => IGPFriends.QueryAsync(() =>
                Task.FromResult(new IGPDesktopSessionCommandResult { Success = false, Code = code, Message = "private-body", ContentJson = FriendJson })).GetAwaiter().GetResult())!;
            Assert.AreEqual(code, error.Code);
            StringAssert.DoesNotContain("private", error.ToString());
        }

        [Test]
        public void TransportFailures_AreSafe()
        {
            var error = Assert.Throws<IGPFriendsException>(() => IGPFriends.QueryAsync(() =>
                Task.FromException<IGPDesktopSessionCommandResult>(new TimeoutException("private-body"))).GetAwaiter().GetResult())!;
            Assert.AreEqual("FRIENDS_TIMEOUT", error.Code);
            StringAssert.DoesNotContain("private-body", error.ToString());
            Assert.Throws<ArgumentNullException>(() => IGPFriends.GetFriendsAsync(null!));
        }

        [Test]
        public void Logs_ContainStagesAndCountWithoutProfiles()
        {
            var messages = new List<string>();
            Application.LogCallback capture = (message, trace, type) => messages.Add(message);
            Application.logMessageReceived += capture;
            IGPLog.Configure(IGPLogLevel.Info);
            try
            {
                IGPFriends.QueryAsync(() => Task.FromResult(new IGPDesktopSessionCommandResult { Success = true, ContentJson = "[" + FriendJson + "]" })).GetAwaiter().GetResult();
                IGPFriends.ExecuteAsync("send-request", () => Task.FromResult(new IGPDesktopSessionCommandResult { Success = true, ContentJson = "{\"result\":\"AUTO_ACCEPTED\"}" }), IGPFriends.ParseActionResponse).GetAwaiter().GetResult();
                Assert.Throws<IGPFriendsException>(() => IGPFriends.ExecuteAsync("accept-request", () => Task.FromException<IGPDesktopSessionCommandResult>(new Exception("private-note credential")), IGPFriends.ParseActionResponse).GetAwaiter().GetResult());
                var logs = string.Join("\n", messages);
                StringAssert.Contains("event=start", logs);
                StringAssert.Contains("event=complete friendCount=1", logs);
                StringAssert.Contains("send-request", logs);
                StringAssert.Contains("event=complete result=success", logs);
                StringAssert.Contains("event=failed", logs);
                StringAssert.DoesNotContain("private-note", logs);
                StringAssert.DoesNotContain("credential", logs);
                StringAssert.DoesNotContain("private-name", logs);
                StringAssert.DoesNotContain("friend-1", logs);
            }
            finally
            {
                Application.logMessageReceived -= capture;
                IGPLog.Configure(IGPLogLevel.Off);
            }
        }
    }
}
