namespace SOR.Game.Handlers; using System.Text.Json; using Microsoft.EntityFrameworkCore; using SOR.Database.Contexts; using SOR.Game.Grid; using SOR.Database.Entities.Catalog; using SOR.Database.Entities.Collection; using SOR.Database.Enums; using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Transport; using SOR.Shared.Networking; /// /// game.ready — player signals they are on the game screen and ready to start. /// /// When BOTH players have sent ready, the game state is initialized and /// pushed to both clients. /// internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler { private readonly IMessageSerializer _serializer; private readonly GameDbContext _gameDb; private readonly SorIdentityDbContext _identityDb; private readonly CollectionDbContext _collectionDb; private readonly CatalogDbContext _catalogDb; private readonly IClientPush _clientPush; public GameReadyHandler( IMessageSerializer serializer, GameDbContext gameDb, SorIdentityDbContext identityDb, CollectionDbContext collectionDb, CatalogDbContext catalogDb, IClientPush clientPush) { _serializer = serializer; _gameDb = gameDb; _identityDb = identityDb; _collectionDb = collectionDb; _catalogDb = catalogDb; _clientPush = clientPush; } public string MessageType => "game.ready"; public async Task HandleAsync( IClientMessage message, AuthenticatedConnection connection, CancellationToken ct) { var req = _serializer.DeserializePayload(message.Payload); var accountId = Guid.Parse(connection.UserId); // Serialize concurrent game.ready requests with a row-level lock so that // exactly one request performs initialization when both players are ready. // Without this, both players send game.ready at nearly the same time (both // clients navigate to the game screen after match_found), each reads the // other's ready flag as false, and neither triggers initialization. await _gameDb.Database.BeginTransactionAsync(ct); var session = await _gameDb.GameSessions .FromSqlInterpolated( $""" SELECT * FROM game.game_sessions WHERE "Id" = {req.SessionId} FOR UPDATE """) .SingleOrDefaultAsync(ct) ?? throw new GameException("SESSION_NOT_FOUND"); bool isP1orP2 = session.PlayerOneAccountId == accountId || session.PlayerTwoAccountId == accountId; bool isAdditional = !isP1orP2 && session.AdditionalPlayersJson != null && session.AdditionalPlayersJson.Contains(accountId.ToString()); if (!isP1orP2 && !isAdditional) throw new GameException("NOT_IN_SESSION"); if (session.Status == GameSessionStatus.Active) { await _gameDb.Database.CommitTransactionAsync(ct); // Fetch the opponent's display name so the client can show it correctly on rejoin. var opponentId = session.PlayerOneAccountId == accountId ? session.PlayerTwoAccountId : session.PlayerOneAccountId; var oppName = await _identityDb.Users .AsNoTracking() .Where(a => a.Id == opponentId) .Select(a => a.DisplayName ?? a.UserName ?? a.Id.ToString().Substring(0, 8)) .FirstOrDefaultAsync(ct); return ServerMessage.Reply("game.ready.ack", message.Seq, new GameReadyResponse(session.Id, "AlreadyStarted", oppName)); } if (session.Status != GameSessionStatus.Initializing) { // Session may already be transitioning/started on another client. // Reply gracefully so clients can recover instead of surfacing hard errors. await _gameDb.Database.CommitTransactionAsync(ct); return ServerMessage.Reply("game.ready.ack", message.Seq, new GameReadyResponse(session.Id, "AlreadyStarted")); } // Mark this player ready. if (session.PlayerOneAccountId == accountId) session.PlayerOneReady = true; else if (session.PlayerTwoAccountId == accountId) session.PlayerTwoReady = true; else if (isAdditional && session.AdditionalPlayersJson != null) { // Additional players (seat 2+): track readiness in AdditionalPlayersJson. var addl = JsonSerializer.Deserialize>( session.AdditionalPlayersJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new(); var entry = addl.FirstOrDefault(p => p.AccountId == accountId); if (entry != null) entry.IsReady = true; session.AdditionalPlayersJson = JsonSerializer.Serialize(addl); } await _gameDb.SaveChangesAsync(ct); bool allReady = session.PlayerOneReady && session.PlayerTwoReady; if (allReady && !string.IsNullOrEmpty(session.AdditionalPlayersJson)) { var addl = JsonSerializer.Deserialize>( session.AdditionalPlayersJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new(); allReady = addl.All(p => p.IsReady); } if (!allReady) { await _gameDb.Database.CommitTransactionAsync(ct); return ServerMessage.Reply("game.ready.ack", message.Seq, new GameReadyResponse(session.Id, "WaitingForOpponent")); } // Both ready — initialize game state. // Deserialize rule snapshot (falls back to default if none stored). var rules = session.RuleSnapshotJson is not null ? GameEngine.DeserializeRules(session.RuleSnapshotJson) : null; GameState state; if (session.PlayerCount <= 2 || string.IsNullOrEmpty(session.AdditionalPlayersJson)) { // Standard 2-player path. var p1DeckCards = await LoadDeckCardsAsync(session.PlayerOneDeckId, ct); var p2DeckCards = await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct); var p1ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct); var p2ArchSpirit = await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct); state = GameEngine.Initialize( session.Id, session.PlayerOneAccountId, p1DeckCards, p1ArchSpirit, session.PlayerTwoAccountId, p2DeckCards, p2ArchSpirit, rules); } else { // N-player path: read additional players from session JSON. var additionalEntries = JsonSerializer.Deserialize>( session.AdditionalPlayersJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? new(); // Build player list with seat/team indices. // P1 and P2 always have seatIndex 0 and 1; teamIndex from GameMode. int teamCount = 1; // FFA default static int TeamIdx(string gameMode, int seat, int tc) => gameMode == "FFA" ? seat : seat % tc; var playerList = new List<(Guid, IEnumerable<(SOR.Database.Entities.Catalog.CardDefinition, int)>, SOR.Database.Entities.Catalog.CardDefinition, int, int)> { (session.PlayerOneAccountId, await LoadDeckCardsAsync(session.PlayerOneDeckId, ct), await LoadDeckArchSpiritAsync(session.PlayerOneDeckId, ct), 0, TeamIdx(session.GameMode, 0, teamCount)), (session.PlayerTwoAccountId, await LoadDeckCardsAsync(session.PlayerTwoDeckId, ct), await LoadDeckArchSpiritAsync(session.PlayerTwoDeckId, ct), 1, TeamIdx(session.GameMode, 1, teamCount)), }; foreach (var entry in additionalEntries) { playerList.Add(( entry.AccountId, await LoadDeckCardsAsync(entry.DeckId, ct), await LoadDeckArchSpiritAsync(entry.DeckId, ct), entry.SeatIndex, entry.TeamIndex)); } var boardShape = rules?.BoardShape is null or "" or "Default" ? BoardShapeGenerator.AutoShape(playerList.Count) : rules.BoardShape; state = GameEngine.Initialize( session.Id, playerList.AsReadOnly(), session.GameMode, boardShape, rules); } // Resolve display names for all players so every client can show real names. var pidGuids = state.Players.Keys .Select(k => Guid.TryParse(k, out var g) ? g : Guid.Empty) .Where(g => g != Guid.Empty) .ToArray(); var nameMap = await _identityDb.Users .AsNoTracking() .Where(u => pidGuids.Contains(u.Id)) .Select(u => new { u.Id, Name = u.DisplayName ?? u.UserName ?? u.Id.ToString().Substring(0, 8) }) .ToDictionaryAsync(u => u.Id.ToString(), u => u.Name, ct); foreach (var (pid, ps) in state.Players) if (nameMap.TryGetValue(pid, out var dn)) ps.DisplayName = dn; session.StateJson = GameEngine.Serialize(state); session.Status = GameSessionStatus.Active; session.StartedAt = DateTimeOffset.UtcNow; await _gameDb.SaveChangesAsync(ct); await _gameDb.Database.CommitTransactionAsync(ct); // Push initial state to both players. await PushStateToPlayersAsync(_clientPush, session, state, ct); return ServerMessage.Reply("game.ready.ack", message.Seq, new GameReadyResponse(session.Id, "Started")); } // ── Helpers ─────────────────────────────────────────────────────────────── /// JSON shape for AdditionalPlayersJson entries on a GameSession. private sealed class SessionAdditionalPlayer { public Guid AccountId { get; set; } public Guid DeckId { get; set; } public int SeatIndex { get; set; } public int TeamIndex { get; set; } public bool IsReady { get; set; } } private async Task> LoadDeckCardsAsync(Guid deckId, CancellationToken ct) { var deck = await _collectionDb.Decks .AsNoTracking() .Include(d => d.Cards) .FirstOrDefaultAsync(d => d.Id == deckId, ct) ?? throw new GameException("DECK_NOT_FOUND"); var defIds = deck.Cards.Select(c => c.CardDefinitionId).ToList(); var defs = await _catalogDb.Set() .AsNoTracking() .Where(d => defIds.Contains(d.Id)) .ToDictionaryAsync(d => d.Id, ct); return deck.Cards .Where(c => defs.ContainsKey(c.CardDefinitionId)) .Select(c => (defs[c.CardDefinitionId], c.Quantity)); } private async Task LoadDeckArchSpiritAsync(Guid deckId, CancellationToken ct) { var deck = await _collectionDb.Decks .AsNoTracking() .FirstOrDefaultAsync(d => d.Id == deckId, ct) ?? throw new GameException("DECK_NOT_FOUND"); if (deck.ArchSpiritCardDefinitionId == Guid.Empty) throw new GameException("DECK_HAS_NO_ARCH_SPIRIT"); return await _catalogDb.Set() .AsNoTracking() .FirstOrDefaultAsync(d => d.Id == deck.ArchSpiritCardDefinitionId, ct) ?? throw new GameException("ARCH_SPIRIT_DEFINITION_NOT_FOUND"); } }