#nullable enable
using System;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IGP.UnitySDK.GameKit
{
    internal static class IGPMatchResultReportSerializer
    {
        internal static string Serialize(IGPMatchResultReport report)
        {
            if (report == null) throw new ArgumentNullException(nameof(report));
            if (report.schemaVersion != 2 ||
                string.IsNullOrWhiteSpace(report.reportId) ||
                string.IsNullOrWhiteSpace(report.matchId) ||
                (report.result != "COMPLETED" && report.result != "ABORTED" && report.result != "FORFEITED") ||
                report.startedAtUnixMs < 0 || report.finishedAtUnixMs < report.startedAtUnixMs ||
                report.players == null || report.players.Length < 1 || report.players.Length > 256)
            {
                throw new ArgumentException("Invalid match result report fields or participant count.", nameof(report));
            }

            foreach (var player in report.players)
            {
                if (player == null || string.IsNullOrWhiteSpace(player.playerId))
                    throw new ArgumentException("Invalid match result participant.", nameof(report));
            }

            string json;
            try
            {
                var serializer = JsonSerializer.Create(new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    TypeNameHandling = TypeNameHandling.None,
                });
                json = JObject.FromObject(report, serializer).ToString(Formatting.None);
            }
            catch (Exception)
            {
                // Serializer exceptions can contain game data or values from custom getters.
                throw new ArgumentException("Match result report is not JSON-serializable.", nameof(report));
            }

            if (Encoding.UTF8.GetByteCount(json) > 64 * 1024)
                throw new ArgumentException("Match result report exceeds 64 KiB of UTF-8 JSON.", nameof(report));
            return json;
        }
    }
}
