namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
///
/// game.transition — active player swaps their ArchSpirit with a Tier 1 ArchSpirit
/// from hand (§6.7.1).
///
/// The outgoing ArchSpirit goes to discard; the incoming enters at the same board
/// position with full HP, Defense, and MP. Cost is the incoming ArchSpirit's SP/ST cost.
/// The incoming ArchSpirit may move, attack, and use abilities the turn it enters.
///
internal sealed class GameTransitionHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameTransitionHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.transition";
public async Task HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload(message.Payload);
var actorId = connection.UserId;
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
var prevStateJson = session.StateJson!;
var state = GameEngine.Deserialize(prevStateJson);
var newState = GameEngine.Transition(state, actorId, req.IncomingCardInstanceId);
var dto = GameEngine.ToDto(newState, actorId);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.transition",
JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.transition.ack", message.Seq,
new GameTransitionResponse(dto));
}
}