namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Database.Entities.Collection;
using SOR.Database.Enums;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
///
/// collection.add_card — adds (or increments) a card in a deck.
///
/// Validation:
/// - Deck exists and belongs to the player.
/// - CardDefinitionId must not be an ArchSpirit (those live at the deck level).
/// - Player owns enough physical copies (existing + delta ≤ owned).
/// - Adding would not push the definition over MaxCopiesPerCard.
/// - Adding would not push the deck over MaxDeckSize.
///
internal sealed class CollectionAddCardHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionAddCardHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.add_card";
public async Task HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload(message.Payload);
var accountId = Guid.Parse(connection.UserId);
if (req.Quantity < 1)
return ServerMessage.Error(message.Seq, "INVALID_QUANTITY", "Quantity must be at least 1.");
// ── Fetch deck ─────────────────────────────────────────────────────────
var deck = await _collectionDb.Decks
.Include(d => d.Cards)
.FirstOrDefaultAsync(
d => d.Id == req.DeckId && d.AccountId == accountId,
cancellationToken);
if (deck == null)
return ServerMessage.Error(message.Seq, "DECK_NOT_FOUND", "Deck not found.");
// ── Validate card type (ArchSpirits cannot be added to the card list) ──
var cardType = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == req.CardDefinitionId)
.Select(cd => (CardType?)cd.CardType)
.FirstOrDefaultAsync(cancellationToken);
if (cardType == null)
return ServerMessage.Error(message.Seq, "CARD_NOT_FOUND", "Card definition not found.");
if (cardType == CardType.ArchSpirit)
return ServerMessage.Error(message.Seq, "ARCH_SPIRIT_NOT_ALLOWED",
"ArchSpirit cards are set at the deck level, not in the card list.");
// ── Copy-count checks ──────────────────────────────────────────────────
var existingEntry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
int currentInDeck = existingEntry?.Quantity ?? 0;
int afterAdd = currentInDeck + req.Quantity;
if (afterAdd > DeckRules.MaxCopiesPerCard)
return ServerMessage.Error(message.Seq, "COPY_LIMIT_EXCEEDED",
$"You may only include up to {DeckRules.MaxCopiesPerCard} copies of a card.");
// ── Deck size check ────────────────────────────────────────────────────
int currentTotal = deck.Cards.Sum(c => c.Quantity);
if (currentTotal + req.Quantity > DeckRules.MaxDeckSize)
return ServerMessage.Error(message.Seq, "DECK_TOO_LARGE",
$"Deck would exceed the maximum of {DeckRules.MaxDeckSize} cards.");
// ── Ownership check ────────────────────────────────────────────────────
int owned = await _collectionDb.PlayerCards
.CountAsync(
pc => pc.AccountId == accountId
&& pc.CardDefinitionId == req.CardDefinitionId,
cancellationToken);
if (owned < afterAdd)
return ServerMessage.Error(message.Seq, "INSUFFICIENT_COPIES",
$"You own {owned} cop{(owned == 1 ? "y" : "ies")} of that card but the deck would need {afterAdd}.");
// ── Apply the change ───────────────────────────────────────────────────
if (existingEntry != null)
{
existingEntry.Quantity = afterAdd;
}
else
{
var entry = new DeckCard
{
DeckId = deck.Id,
CardDefinitionId = req.CardDefinitionId,
Quantity = req.Quantity,
};
_collectionDb.DeckCards.Add(entry);
deck.Cards.Add(entry);
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
// Return the updated deck summary.
var archName = await _catalogDb.CardDefinitions
.Where(cd => cd.Id == deck.ArchSpiritCardDefinitionId)
.Select(cd => cd.Name)
.FirstOrDefaultAsync(cancellationToken);
var summary = new DeckSummaryDto(
Id: deck.Id,
Name: deck.Name,
ArchSpiritCardDefinitionId: deck.ArchSpiritCardDefinitionId,
ArchSpiritName: archName,
CardCount: deck.Cards.Sum(c => c.Quantity),
IsValid: deck.IsValid,
CreatedAt: deck.CreatedAt,
UpdatedAt: deck.UpdatedAt);
return ServerMessage.Reply("collection.add_card.ack", message.Seq,
new DeckMutationResponse(summary));
}
}