#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using IGP.UnitySDK.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IGP.UnitySDK.GameKit
{
    [Serializable]
    public sealed class IGPFriendRequestActionResult
    {
        public string result = string.Empty;
    }

    [Serializable]
    public sealed class IGPIncomingFriendRequest
    {
        public string friendshipId = string.Empty;
        public IGPPlayerProfile profile = new IGPPlayerProfile();
        public string? note;
        public string? requestedAt;
    }

    public enum IGPFriendOnlineStatus
    {
        Offline = 0,
        Online = 1
    }

    [Serializable]
    public sealed class IGPFriend
    {
        public IGPPlayerProfile profile = new IGPPlayerProfile();
        public IGPFriendOnlineStatus onlineStatus;
    }

    public sealed class IGPFriendsException : Exception
    {
        public IGPFriendsException(string code, string message) : base(message)
        {
            Code = code ?? string.Empty;
        }

        public string Code { get; }
    }

    public static class IGPFriends
    {
        /// <summary>Sends through Host. The result can include AUTO_ACCEPTED for a reciprocal request.</summary>
        public static Task<IGPFriendRequestActionResult> SendFriendRequestAsync(
            IGPRuntimeManager runtimeManager, string userId, CancellationToken cancellationToken = default)
        {
            if (runtimeManager == null) throw new ArgumentNullException(nameof(runtimeManager));
            return ExecuteAsync("send-request", () => runtimeManager.SendDesktopFriendCommandAsync(
                IGPDesktopSessionCommandType.SendDesktopFriendRequest,
                JsonConvert.SerializeObject(new { targetUserId = RequireId(userId, nameof(userId)) }),
                cancellationToken), ParseActionResponse, cancellationToken);
        }

        /// <summary>Fetches a fresh snapshot without marking requests viewed.</summary>
        public static Task<IGPIncomingFriendRequest[]> GetIncomingFriendRequestsAsync(
            IGPRuntimeManager runtimeManager, CancellationToken cancellationToken = default)
        {
            if (runtimeManager == null) throw new ArgumentNullException(nameof(runtimeManager));
            return ExecuteAsync("get-incoming", () => runtimeManager.SendDesktopFriendCommandAsync(
                IGPDesktopSessionCommandType.GetDesktopIncomingFriendRequests, null, cancellationToken),
                ParseIncomingResponse, cancellationToken);
        }

        /// <summary>Accepts by friendship ID from an incoming snapshot, not by player ID.</summary>
        public static Task<IGPFriendRequestActionResult> AcceptFriendRequestAsync(
            IGPRuntimeManager runtimeManager, string friendshipId, CancellationToken cancellationToken = default)
        {
            if (runtimeManager == null) throw new ArgumentNullException(nameof(runtimeManager));
            return ExecuteAsync("accept-request", () => runtimeManager.SendDesktopFriendCommandAsync(
                IGPDesktopSessionCommandType.AcceptDesktopFriendRequest,
                JsonConvert.SerializeObject(new { friendshipId = RequireId(friendshipId, nameof(friendshipId)) }),
                cancellationToken), ParseActionResponse, cancellationToken);
        }

        private static string RequireId(string value, string parameterName)
        {
            if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Identifier is required", parameterName);
            return value;
        }

        internal static async Task<T> ExecuteAsync<T>(string operation,
            Func<Task<IGPDesktopSessionCommandResult>> send, Func<string?, T> parse,
            CancellationToken cancellationToken = default)
        {
            IGPLog.Info("game-kit-friends", operation, "event=start");
            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                var response = await send();
                if (response == null) throw InvalidResponse();
                if (!response.Success)
                    throw new IGPFriendsException(SafeCode(response.Code), "Desktop friend request command failed");
                var value = parse(response.ContentJson);
                IGPLog.Info("game-kit-friends", operation, "event=complete result=success");
                return value;
            }
            catch (Exception exception)
            {
                IGPLog.Warning("game-kit-friends", operation, $"event=failed errorType={exception.GetType().Name}");
                if (exception is IGPFriendsException) throw;
                if (exception is OperationCanceledException)
                    throw new OperationCanceledException("Desktop friend request command was canceled", cancellationToken);
                if (exception is ArgumentException)
                    throw new IGPFriendsException("FRIENDS_INVALID_INPUT", "Friend identifier is required");
                throw new IGPFriendsException(exception is IGPSDKException sdkException
                    ? SafeCode(sdkException.ErrorCode)
                    : exception is TimeoutException ? "FRIENDS_TIMEOUT" : "FRIENDS_REQUEST_FAILED",
                    "Desktop friend request command failed");
            }
        }

        internal static IGPFriendRequestActionResult ParseActionResponse(string? json)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(json)) throw InvalidResponse();
                var row = JObject.Parse(json!);
                if (row["result"]?.Type != JTokenType.String ||
                    string.IsNullOrWhiteSpace((string?)row["result"])) throw InvalidResponse();
                return new IGPFriendRequestActionResult { result = (string)row["result"]! };
            }
            catch (JsonException) { throw InvalidResponse(); }
        }

        internal static IGPIncomingFriendRequest[] ParseIncomingResponse(string? json)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(json)) throw InvalidResponse();
                var rows = JArray.Parse(json!);
                var requests = new IGPIncomingFriendRequest[rows.Count];
                for (var i = 0; i < rows.Count; i++)
                {
                    if (!(rows[i] is JObject row) ||
                        row["friendshipId"]?.Type != JTokenType.String ||
                        string.IsNullOrWhiteSpace((string?)row["friendshipId"]) ||
                        !(row["profile"] is JObject profile) ||
                        profile["id"]?.Type != JTokenType.String ||
                        string.IsNullOrWhiteSpace((string?)profile["id"]) ||
                        !IsNullableString(profile["nickname"]) ||
                        !IsNullableString(profile["avatarUrl"]) ||
                        !IsNullableString(profile["avatarFrameUrl"]) ||
                        !IsNullableString(row["note"]) || !IsNullableString(row["requestedAt"]))
                        throw InvalidResponse();
                    requests[i] = new IGPIncomingFriendRequest
                    {
                        friendshipId = (string)row["friendshipId"]!,
                        profile = new IGPPlayerProfile
                        {
                            id = (string)profile["id"]!, nickname = (string?)profile["nickname"],
                            avatarUrl = (string?)profile["avatarUrl"], avatarFrameUrl = (string?)profile["avatarFrameUrl"]
                        },
                        note = (string?)row["note"], requestedAt = (string?)row["requestedAt"]
                    };
                }
                return requests;
            }
            catch (JsonException) { throw InvalidResponse(); }
        }

        /// <summary>
        /// Queries the signed-in Desktop user's friends. Offline includes unconfirmed presence.
        /// Call again to refresh; this method does not subscribe to changes.
        /// </summary>
        public static Task<IGPFriend[]> GetFriendsAsync(IGPRuntimeManager runtimeManager)
        {
            if (runtimeManager == null) throw new ArgumentNullException(nameof(runtimeManager));
            return QueryAsync(runtimeManager.GetDesktopFriendsAsync);
        }

        internal static async Task<IGPFriend[]> QueryAsync(
            Func<Task<IGPDesktopSessionCommandResult>> send)
        {
            IGPLog.Info("game-kit-friends", "get", "event=start");
            try
            {
                var result = await send();
                if (result == null)
                    throw InvalidResponse();
                if (!result.Success)
                    throw new IGPFriendsException(SafeCode(result.Code), "Desktop friends command failed");

                var friends = ParseResponse(result.ContentJson);
                IGPLog.Info("game-kit-friends", "get", $"event=complete friendCount={friends.Length}");
                return friends;
            }
            catch (Exception exception)
            {
                IGPLog.Warning("game-kit-friends", "get", $"event=failed errorType={exception.GetType().Name}");
                if (exception is IGPFriendsException) throw;
                if (exception is OperationCanceledException)
                    throw new OperationCanceledException("Desktop friends query was canceled");
                throw new IGPFriendsException(
                    exception is IGPSDKException sdkException
                        ? SafeCode(sdkException.ErrorCode)
                        : exception is TimeoutException ? "FRIENDS_TIMEOUT" : "FRIENDS_QUERY_FAILED",
                    "Desktop friends query failed");
            }
        }

        internal static IGPFriend[] ParseResponse(string? contentJson)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(contentJson)) throw InvalidResponse();
                var rows = JArray.Parse(contentJson!);
                var friends = new IGPFriend[rows.Count];
                for (var index = 0; index < rows.Count; index++)
                {
                    if (!(rows[index] is JObject row) || row.Count != 2 ||
                        !(row["profile"] is JObject profile) || profile.Count != 4 ||
                        profile["id"]?.Type != JTokenType.String ||
                        string.IsNullOrWhiteSpace((string?)profile["id"]) ||
                        !IsNullableString(profile["nickname"]) ||
                        !IsNullableString(profile["avatarUrl"]) ||
                        !IsNullableString(profile["avatarFrameUrl"]) ||
                        row["onlineStatus"]?.Type != JTokenType.String)
                        throw InvalidResponse();

                    var status = (string?)row["onlineStatus"];
                    if (status != "offline" && status != "online") throw InvalidResponse();
                    friends[index] = new IGPFriend
                    {
                        profile = new IGPPlayerProfile
                        {
                            id = (string)profile["id"]!,
                            nickname = (string?)profile["nickname"],
                            avatarUrl = (string?)profile["avatarUrl"],
                            avatarFrameUrl = (string?)profile["avatarFrameUrl"]
                        },
                        onlineStatus = status == "online" ? IGPFriendOnlineStatus.Online : IGPFriendOnlineStatus.Offline
                    };
                }
                return friends;
            }
            catch (JsonException)
            {
                throw InvalidResponse();
            }
        }

        private static bool IsNullableString(JToken? token) =>
            token != null && (token.Type == JTokenType.String || token.Type == JTokenType.Null);

        private static IGPFriendsException InvalidResponse() =>
            new IGPFriendsException("FRIENDS_INVALID_RESPONSE", "Desktop friends response is invalid");

        private static string SafeCode(string? code)
        {
            if (string.IsNullOrEmpty(code) || code!.Length > 64) return "FRIENDS_QUERY_FAILED";
            foreach (var character in code)
                if (!(character >= 'A' && character <= 'Z') &&
                    !(character >= '0' && character <= '9') && character != '_')
                    return "FRIENDS_QUERY_FAILED";
            return code;
        }
    }
}
