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.ascend — active player upgrades their ArchSpirit by exactly one tier (§6.7.2).
///
/// The incoming higher-tier ArchSpirit must be the direct next tier in the ascension chain
/// (Tier+1, PreviousTierId == current ArchSpirit's CardDefinitionId). It may come from
/// any zone (hand, deck, or discard). Cost is the incoming ArchSpirit's SP/ST cost.
/// The new ArchSpirit enters at the current position with full HP, Defense, and MP.
///
internal sealed class GameAscendHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameAscendHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.ascend";
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.Ascend(state, actorId, req.IncomingCardInstanceId);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.ascend",
JsonSerializer.Serialize(req), ct);
var dto = GameEngine.ToDto(newState, actorId);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.ascend.ack", message.Seq,
new GameAscendResponse(dto));
}
}