namespace SOR.Collection.Handlers;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
///
/// collection.remove_card — removes copies of a card from a deck.
///
/// If Quantity is null or ≥ current quantity, the card is removed entirely.
/// If Quantity is a positive int, that many copies are decremented.
///
internal sealed class CollectionRemoveCardHandler : CollectionHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb;
public CollectionRemoveCardHandler(
IMessageSerializer serializer,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb)
{
_serializer = serializer;
_collectionDb = collectionDb;
_catalogDb = catalogDb;
}
public string MessageType => "collection.remove_card";
public async Task HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken cancellationToken)
{
var req = _serializer.DeserializePayload(message.Payload);
var accountId = Guid.Parse(connection.UserId);
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.");
var entry = deck.Cards.FirstOrDefault(c => c.CardDefinitionId == req.CardDefinitionId);
if (entry == null)
return ServerMessage.Error(message.Seq, "CARD_NOT_IN_DECK",
"That card is not in this deck.");
int toRemove = req.Quantity is null or <= 0 ? entry.Quantity : req.Quantity.Value;
if (toRemove >= entry.Quantity)
{
// Remove the row entirely.
_collectionDb.DeckCards.Remove(entry);
deck.Cards.Remove(entry);
}
else
{
entry.Quantity -= toRemove;
}
await RefreshValidityAsync(_collectionDb, deck, cancellationToken);
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.remove_card.ack", message.Seq,
new DeckMutationResponse(summary));
}
}