using DataServer.Data; using DataServer.Data.Entities; using DataServer.Data.Enums; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Server.Networking; using Server.Networking.Messages; namespace GameServer.Dungeon; public sealed partial class DungeonHandler { private sealed class NpcInteractRequest { public int NpcId { get; set; } } private sealed class NpcDialogSelectRequest { public int NpcId { get; set; } public int OptionId { get; set; } } private sealed class NpcShopActionRequest { public int NpcId { get; set; } public string Action { get; set; } = "buy"; public int SlotIndex { get; set; } public int Quantity { get; set; } = 1; } private async Task HandleNpcInteract(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) { await SendErrorAsync(connection, "not_in_dungeon", ct); return; } var req = _ser.Deserialize(payload); if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc)) { await SendAsync(connection, DungeonOpCodes.NPC_INTERACT_STATE, new { success = false, error = "npc_not_found" }, ct); return; } await SendAsync(connection, DungeonOpCodes.NPC_INTERACT_STATE, new { success = true, npc = new { id = npc.Id, definitionId = npc.DefinitionId, name = npc.Name, canShop = npc.CanShop, hasDialog = npc.HasDialog, isKillable = npc.IsKillable, behavior = npc.BehaviorMode.ToString().ToLower(), onAttackBehavior = npc.OnAttackBehavior.ToString().ToLower(), shopId = npc.ShopId, dialogTreeId = npc.DialogTreeId } }, ct); if (npc.HasDialog && npc.DialogTreeId.HasValue) { await SendNpcDialogNodeAsync(connection, session, npc, null, ct); } if (npc.CanShop && npc.ShopId.HasValue) { await SendNpcShopStateAsync(connection, npc.ShopId.Value, ct); } } private async Task HandleNpcDialogSelect(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) { await SendErrorAsync(connection, "not_in_dungeon", ct); return; } var req = _ser.Deserialize(payload); if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc) || !npc.HasDialog || !npc.DialogTreeId.HasValue) { await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new { success = false, error = "npc_dialog_unavailable" }, ct); return; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var option = await db.DungeonNpcDialogOptions .Include(o => o.Node) .FirstOrDefaultAsync(o => o.Id == req.OptionId, ct); if (option == null || option.Node == null || option.Node.DialogTreeId != npc.DialogTreeId.Value) { await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new { success = false, error = "invalid_option" }, ct); return; } var (conditionMet, conditionError) = await EvaluateDialogConditionAsync(db, session, option, ct); if (!conditionMet) { await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new { success = false, error = conditionError ?? "condition_failed" }, ct); return; } if (option.ConsumeConditionItem && option.ConditionType == NpcDialogConditionType.HasItem && int.TryParse(option.ConditionValue, out var consumeItemDefId)) { await ConsumeCharacterItemAsync(db, session.CharacterId, consumeItemDefId, Math.Max(1, option.ConditionQuantity), ct); } var nextNode = option.NextNodeId.HasValue ? await db.DungeonNpcDialogNodes.FirstOrDefaultAsync(n => n.Id == option.NextNodeId.Value && n.DialogTreeId == npc.DialogTreeId.Value, ct) : null; if (nextNode != null) { await ApplyNpcDialogRewardsAsync(db, session, nextNode, ct); await SendNpcDialogNodeAsync(connection, session, npc, nextNode.Id, ct); await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new { success = true, npcId = npc.Id, nextNodeId = nextNode.Id, isTerminal = nextNode.IsTerminal }, ct); return; } await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_RESULT, new { success = true, npcId = npc.Id, nextNodeId = (int?)null, isTerminal = true }, ct); } private async Task HandleNpcShopAction(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) { if (!session.CurrentDungeonId.HasValue || !_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) { await SendErrorAsync(connection, "not_in_dungeon", ct); return; } var req = _ser.Deserialize(payload); if (!dungeon.Simulation.Npcs.TryGetValue(req.NpcId, out var npc) || !npc.CanShop || !npc.ShopId.HasValue) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "npc_shop_unavailable" }, ct); return; } if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase)) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "unsupported_shop_action", message = "Only buy is currently supported." }, ct); return; } using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var shopItem = await db.DungeonNpcShopItems .Include(s => s.ItemDefinition) .FirstOrDefaultAsync(s => s.ShopId == npc.ShopId.Value && s.SlotIndex == req.SlotIndex, ct); if (shopItem == null || shopItem.ItemDefinition == null) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "shop_item_not_found" }, ct); return; } var quantity = Math.Max(1, req.Quantity); if (!shopItem.Restocks) { quantity = Math.Min(quantity, shopItem.Quantity); if (quantity <= 0) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "out_of_stock" }, ct); return; } } var totalPrice = shopItem.PriceGold * quantity; var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == session.CharacterId, ct); if (character == null) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "character_not_found" }, ct); return; } if (character.Gold < totalPrice) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "not_enough_gold", requiredGold = totalPrice, currentGold = character.Gold }, ct); return; } var added = await AddItemToCharacterInventoryAsync( db, session.CharacterId, shopItem.ItemDefinitionId, quantity, ct); if (!added) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = false, error = "inventory_full" }, ct); return; } character.Gold -= totalPrice; if (!shopItem.Restocks) { shopItem.Quantity = Math.Max(0, shopItem.Quantity - quantity); } await db.SaveChangesAsync(ct); session.Character.Gold = character.Gold; await SendAsync(connection, DungeonOpCodes.NPC_SHOP_RESULT, new { success = true, npcId = npc.Id, action = "buy", itemDefinitionId = shopItem.ItemDefinitionId, quantity, totalPrice, remainingGold = character.Gold, remainingStock = shopItem.Quantity }, ct); await HandleInventoryRequest(connection, session, ct); await SendNpcShopStateAsync(connection, npc.ShopId.Value, ct); } private async Task SendNpcDialogNodeAsync(IConnection connection, DungeonPlayerSession session, NpcInstance npc, int? nodeId, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); DungeonNpcDialogNode? node; if (nodeId.HasValue) { node = await db.DungeonNpcDialogNodes .FirstOrDefaultAsync(n => n.Id == nodeId.Value && n.DialogTreeId == npc.DialogTreeId, ct); } else { node = await db.DungeonNpcDialogNodes .FirstOrDefaultAsync(n => n.DialogTreeId == npc.DialogTreeId && n.IsRoot, ct); } if (node == null) { await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_STATE, new { success = false, error = "dialog_node_not_found", npcId = npc.Id }, ct); return; } var options = await db.DungeonNpcDialogOptions .Where(o => o.NodeId == node.Id) .OrderBy(o => o.SortOrder) .ToListAsync(ct); var filtered = new List(); foreach (var option in options) { var (ok, _) = await EvaluateDialogConditionAsync(db, session, option, ct); if (!ok) continue; filtered.Add(new { id = option.Id, text = option.PlayerText, nextNodeId = option.NextNodeId }); } await SendAsync(connection, DungeonOpCodes.NPC_DIALOG_STATE, new { success = true, npcId = npc.Id, node = new { id = node.Id, text = node.Text, isTerminal = node.IsTerminal, rewardGold = node.RewardGold, rewardXp = node.RewardXp, rewardItemDefinitionId = node.RewardItemDefinitionId, rewardItemQuantity = node.RewardItemQuantity, rewardQuestKey = node.RewardQuestKey }, options = filtered }, ct); } private async Task SendNpcShopStateAsync(IConnection connection, int shopId, CancellationToken ct) { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var shop = await db.DungeonNpcShops .Include(s => s.Items) .ThenInclude(i => i.ItemDefinition) .FirstOrDefaultAsync(s => s.Id == shopId && s.IsEnabled, ct); if (shop == null) { await SendAsync(connection, DungeonOpCodes.NPC_SHOP_STATE, new { success = false, error = "shop_not_found" }, ct); return; } var now = DateTime.UtcNow; foreach (var item in shop.Items.Where(i => i.Restocks && i.RestockIntervalSeconds > 0 && i.LastRestockAt.HasValue)) { if ((now - item.LastRestockAt.Value).TotalSeconds >= item.RestockIntervalSeconds) { item.LastRestockAt = now; } } await db.SaveChangesAsync(ct); await SendAsync(connection, DungeonOpCodes.NPC_SHOP_STATE, new { success = true, shop = new { id = shop.Id, name = shop.Name, items = shop.Items.OrderBy(i => i.SlotIndex).Select(i => new { slotIndex = i.SlotIndex, itemDefinitionId = i.ItemDefinitionId, itemName = i.ItemDefinition != null ? i.ItemDefinition.Name : $"Item {i.ItemDefinitionId}", quantity = i.Quantity, priceGold = i.PriceGold, restocks = i.Restocks, restockIntervalSeconds = i.RestockIntervalSeconds }) } }, ct); } private async Task<(bool Ok, string? Error)> EvaluateDialogConditionAsync(GameDbContext db, DungeonPlayerSession session, DungeonNpcDialogOption option, CancellationToken ct) { switch (option.ConditionType) { case NpcDialogConditionType.None: return (true, null); case NpcDialogConditionType.HasItem: if (!int.TryParse(option.ConditionValue, out var itemDefinitionId)) return (false, "invalid_condition_value"); var itemCount = await db.DungeonCharacterItems .Where(i => i.CharacterId == session.CharacterId && i.ItemDefinitionId == itemDefinitionId) .SumAsync(i => (int?)i.Quantity, ct) ?? 0; return itemCount >= Math.Max(1, option.ConditionQuantity) ? (true, null) : (false, "requires_item"); case NpcDialogConditionType.CharacterLevelAtLeast: if (!int.TryParse(option.ConditionValue, out var minLevel)) return (false, "invalid_condition_value"); return session.Character.Level >= minLevel ? (true, null) : (false, "level_too_low"); case NpcDialogConditionType.CharacterLevelAtMost: if (!int.TryParse(option.ConditionValue, out var maxLevel)) return (false, "invalid_condition_value"); return session.Character.Level <= maxLevel ? (true, null) : (false, "level_too_high"); case NpcDialogConditionType.GoldAtLeast: if (!long.TryParse(option.ConditionValue, out var minGold)) return (false, "invalid_condition_value"); return session.Character.Gold >= minGold ? (true, null) : (false, "not_enough_gold"); // Quest condition wiring will hook into quest service when added. case NpcDialogConditionType.QuestCompleted: case NpcDialogConditionType.QuestActive: return (false, "quest_system_not_ready"); default: return (false, "unsupported_condition"); } } private async Task ApplyNpcDialogRewardsAsync(GameDbContext db, DungeonPlayerSession session, DungeonNpcDialogNode node, CancellationToken ct) { var modified = false; var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == session.CharacterId, ct); if (character == null) return; if (node.RewardGold > 0) { character.Gold += node.RewardGold; session.Character.Gold = character.Gold; modified = true; } if (node.RewardXp > 0) { character.Experience += node.RewardXp; session.Character.Experience = character.Experience; modified = true; } if (node.RewardItemDefinitionId.HasValue && node.RewardItemQuantity > 0) { var added = await AddItemToCharacterInventoryAsync( db, session.CharacterId, node.RewardItemDefinitionId.Value, node.RewardItemQuantity, ct); modified = modified || added; } if (modified) { await db.SaveChangesAsync(ct); } } private async Task AddItemToCharacterInventoryAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) { if (quantity <= 0) return true; var itemDef = await db.DungeonItemDefinitions.FirstOrDefaultAsync(i => i.Id == itemDefinitionId, ct); if (itemDef == null) return false; var inventoryItems = await db.DungeonCharacterItems .Where(i => i.CharacterId == characterId && !i.IsEquipped) .ToListAsync(ct); var remaining = quantity; if (itemDef.Stackable) { foreach (var stack in inventoryItems.Where(i => i.ItemDefinitionId == itemDefinitionId && i.Quantity < itemDef.MaxStack)) { var canAdd = Math.Min(remaining, itemDef.MaxStack - stack.Quantity); if (canAdd <= 0) continue; stack.Quantity += canAdd; remaining -= canAdd; if (remaining <= 0) return true; } } var usedSlots = inventoryItems.Select(i => i.SlotIndex).ToHashSet(); for (var slot = 0; slot < 30 && remaining > 0; slot++) { if (usedSlots.Contains(slot)) continue; var addQty = itemDef.Stackable ? Math.Min(remaining, itemDef.MaxStack) : 1; db.DungeonCharacterItems.Add(new DungeonCharacterItem { CharacterId = characterId, ItemDefinitionId = itemDefinitionId, Quantity = addQty, SlotIndex = slot, IsEquipped = false }); usedSlots.Add(slot); remaining -= addQty; } return remaining <= 0; } private async Task ConsumeCharacterItemAsync(GameDbContext db, ulong characterId, int itemDefinitionId, int quantity, CancellationToken ct) { if (quantity <= 0) return; var items = await db.DungeonCharacterItems .Where(i => i.CharacterId == characterId && i.ItemDefinitionId == itemDefinitionId && !i.IsEquipped) .OrderBy(i => i.SlotIndex) .ToListAsync(ct); var remaining = quantity; foreach (var item in items) { if (remaining <= 0) break; var take = Math.Min(item.Quantity, remaining); item.Quantity -= take; remaining -= take; if (item.Quantity <= 0) { db.DungeonCharacterItems.Remove(item); } } await db.SaveChangesAsync(ct); } }