#nullable enable
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using IGP.Multiplayer.Models;
using IGP.Multiplayer.Protocol;
using IGP.UnitySDK;
using IGP.UnitySDK.Models;

namespace IGP.Multiplayer
{
    /// <summary>
    /// Immutable peer routing context supplied by the RoomNode reliable handshake.
    /// </summary>
    internal sealed class IGPDataPlanePeerContext
    {
        public uint LocalPlayerSlot { get; }
        public uint HostSlot { get; }
        public string HostPlayerId { get; }
        public IReadOnlyDictionary<string, uint> SlotsByPlayerId { get; }

        internal IGPDataPlanePeerContext(IGPDataPlanePeerTable peers)
        {
            if (peers == null) throw new ArgumentNullException(nameof(peers));
            if (!peers.PlayerIdBySlot.TryGetValue(peers.PlayerSlot, out string? localPlayerId) ||
                string.IsNullOrWhiteSpace(localPlayerId))
            {
                throw new IGPSDKException(
                    "Reliable handshake did not provide usable peer routing context",
                    IGPMultiplayerErrorCodes.ERR_DATA_PLANE_PEER_CONTEXT_INVALID);
            }

            LocalPlayerSlot = peers.PlayerSlot;
            HostSlot = peers.HostSlot;
            HostPlayerId = peers.PlayerIdBySlot.TryGetValue(peers.HostSlot, out var hostPlayerId) ? hostPlayerId : string.Empty;
            var slots = new Dictionary<string, uint>(StringComparer.Ordinal);
            foreach (KeyValuePair<string, uint> entry in peers.SlotByPlayerId)
            {
                slots[entry.Key] = entry.Value;
            }
            SlotsByPlayerId = new ReadOnlyDictionary<string, uint>(slots);
        }
    }

    internal static class IGPMultiplayerBootstrapValidator
    {
        internal static void Validate(IGPMultiplayerBootstrap bootstrap)
        {
            if (bootstrap == null) throw Invalid("Multiplayer bootstrap is required");

            IGPMultiplayerRoomSnapshot room = bootstrap.Room;
            IGPMultiplayerPlayerSnapshot player = bootstrap.CurrentPlayer;
            IGPGameDataPlaneDescriptor descriptor = bootstrap.DataPlane;
            if (string.IsNullOrWhiteSpace(room.Id) ||
                !string.Equals(room.Status, "playing", StringComparison.OrdinalIgnoreCase))
            {
                throw Invalid("Multiplayer room identity is missing or the room is not playing");
            }
            if (string.IsNullOrWhiteSpace(player.Id))
            {
                throw Invalid("Multiplayer current-player identity is missing");
            }
            if (!string.Equals(room.Id, descriptor.RoomId, StringComparison.Ordinal) ||
                !string.Equals(player.Id, descriptor.PlayerId, StringComparison.Ordinal))
            {
                throw Invalid("Multiplayer bootstrap contains mismatched room or player identifiers");
            }
            if (string.IsNullOrWhiteSpace(descriptor.MatchId))
                throw new IGPSDKException("SDK descriptor requires a Match identity", "MULTIPLAYER_MATCH_ID_REQUIRED");
            if (descriptor.Mode != 1 ||
                string.IsNullOrWhiteSpace(descriptor.Token) ||
                string.IsNullOrWhiteSpace(descriptor.Host) ||
                descriptor.Port == 0 ||
                descriptor.ExpiresAtUnixMs <= checked((ulong)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()))
            {
                throw Invalid("Multiplayer data-plane descriptor is incomplete or expired");
            }

        }

        private static IGPSDKException Invalid(string message) =>
            new IGPSDKException(message, IGPErrorCodes.ERR_MULTIPLAYER_CONTEXT_INVALID);
    }
}
