namespace SOR.Game; using System.Collections.Concurrent; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SOR.Database.Contexts; using SOR.Database.Enums; using SOR.Game.Handlers; using SOR.Networking.Abstractions.EventBus; using SOR.Networking.Abstractions.Push; /// /// Manages per-session turn timers. When a turn timer expires the active player's /// turn is ended automatically (equivalent to game.end_turn fired by the engine). /// /// Registered as both a singleton (so handlers can inject it) and as an IHostedService /// (so StartAsync / StopAsync are called on application lifecycle events). /// internal sealed class GameTurnTimerService : IHostedService { /// /// Static reference set in the constructor so that FinalizeGameAsync (a static method /// on GameHandlerBase) can cancel timers without requiring DI injection. /// Safe because the service is registered as a singleton. /// internal static GameTurnTimerService? Instance { get; private set; } private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; private readonly ConcurrentDictionary _timers = new(); private CancellationToken _stoppingToken; public GameTurnTimerService(IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; Instance = this; } public Task StartAsync(CancellationToken cancellationToken) { _stoppingToken = cancellationToken; return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { foreach (var cts in _timers.Values) cts.Cancel(); _timers.Clear(); return Task.CompletedTask; } /// /// Reset (or start) the turn timer for a session. Cancels any existing timer first. /// If is 0 the timer is simply cancelled and not restarted. /// The effective deadline is also capped by the session time limit if one is configured. /// public void ResetTimer( Guid sessionId, int turnTimerSeconds, int timeLimitMinutes, DateTimeOffset sessionCreatedAt) { // Cancel the previous turn's timer. if (_timers.TryRemove(sessionId, out var existing)) existing.Cancel(); if (turnTimerSeconds <= 0) return; // No per-turn timer configured. int effectiveSeconds = turnTimerSeconds; // Cap by remaining session time if a time limit is configured. if (timeLimitMinutes > 0) { var elapsed = DateTimeOffset.UtcNow - sessionCreatedAt; var remaining = TimeSpan.FromMinutes(timeLimitMinutes) - elapsed; if (remaining.TotalSeconds <= 0) return; // Session time already exhausted; let the next action resolve it. effectiveSeconds = Math.Min(effectiveSeconds, (int)remaining.TotalSeconds); } var cts = new CancellationTokenSource(); _timers[sessionId] = cts; // Fire-and-forget: run the delay on the thread-pool. _ = RunTimerAsync(sessionId, effectiveSeconds, cts.Token); } /// /// Cancel and remove the timer for a session (called when the game ends normally). /// public void CancelTimer(Guid sessionId) { if (_timers.TryRemove(sessionId, out var cts)) cts.Cancel(); } // ------------------------------------------------------------------------- private async Task RunTimerAsync(Guid sessionId, int seconds, CancellationToken ct) { try { await Task.Delay(TimeSpan.FromSeconds(seconds), ct); await AutoEndTurnAsync(sessionId); } catch (OperationCanceledException) { // Timer was reset or the game ended — nothing to do. } catch (Exception ex) { _logger.LogError(ex, "Turn timer auto-end failed for session {SessionId}", sessionId); } } private async Task AutoEndTurnAsync(Guid sessionId) { using var scope = _scopeFactory.CreateScope(); var sp = scope.ServiceProvider; var gameDb = sp.GetRequiredService(); var identityDb = sp.GetRequiredService(); var clientPush = sp.GetRequiredService(); var eventBus = sp.GetRequiredService(); // Acquire a row-level lock, same pattern as LoadActiveSessionAsync. await gameDb.Database.BeginTransactionAsync(_stoppingToken); var session = await gameDb.GameSessions .FromSqlInterpolated( $""" SELECT * FROM game.game_sessions WHERE "Id" = {sessionId} FOR UPDATE """) .SingleOrDefaultAsync(_stoppingToken); if (session is null || session.Status != GameSessionStatus.Active) { // Game ended before the timer fired — roll back and exit cleanly. await gameDb.Database.RollbackTransactionAsync(_stoppingToken); return; } var state = GameEngine.Deserialize(session.StateJson!); var actorId = state.ActivePlayerAccountId; var (newState, gameOver) = GameEngine.EndTurn(state, actorId); if (gameOver) { var dto = GameEngine.ToDto(newState, actorId); await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId, "game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto)); await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken); bool isMulti = session.PlayerCount > 2 || !string.IsNullOrEmpty(session.AdditionalPlayersJson); if (isMulti) { var (winnerIds, loserIds) = GameEngine.GetNPlayerTurnLimitWinners(newState); session.Status = GameSessionStatus.Completed; session.WinnerAccountId = winnerIds.FirstOrDefault(); session.WinCondition = "turn_limit"; session.EndedAt = DateTimeOffset.UtcNow; await GameHandlerBase.FinalizeMultiPlayerGameAsync( gameDb, identityDb, clientPush, eventBus, session, winnerIds, loserIds, "turn_limit", _stoppingToken); } else { var (winnerId, loserId) = GameEngine.GetTurnLimitWinner(newState); session.Status = GameSessionStatus.Completed; session.WinnerAccountId = winnerId; session.WinCondition = "turn_limit"; session.EndedAt = DateTimeOffset.UtcNow; await GameHandlerBase.FinalizeGameAsync( gameDb, identityDb, clientPush, eventBus, session, winnerId, loserId, "turn_limit", _stoppingToken); } } else { var dto = GameEngine.ToDto(newState, actorId); await GameHandlerBase.SaveStateAsync(gameDb, session, newState, actorId, "game.turn_timer_expired", null, _stoppingToken, JsonSerializer.Serialize(dto)); await GameHandlerBase.PushStateToPlayersAsync(clientPush, session, newState, _stoppingToken); // Start the timer for the new active player's turn. ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, newState.Rules.TimeLimitMinutes, session.CreatedAt); } } }