using System.Collections.Concurrent; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using DataServer.Data; namespace Server.Game; /// /// Interface for item data access /// public interface IItemService { GameItemData? GetItem(int id); GameRecipeData? GetRecipe(int id); IReadOnlyList GetAllItems(); IReadOnlyList GetAllRecipes(); IReadOnlyList GetItemsByCategory(ItemCategory category); Task ReloadCacheAsync(); } /// /// Runtime item data (cached from database) /// public sealed class GameItemData { public int Id { get; init; } public string Name { get; init; } = ""; public ItemCategory Category { get; init; } public int CraftCost { get; init; } public string Description { get; init; } = ""; public int LootValue { get; init; } public bool Stackable { get; init; } // Weapon stats public int Damage { get; init; } public float FireRate { get; init; } public float ProjectileSpeed { get; init; } public float Range { get; init; } public int AmmoType { get; init; } public int PelletCount { get; init; } = 1; public float Spread { get; init; } public float ExplosionRadius { get; init; } // Tool stats public float HarvestMultiplier { get; init; } = 1f; public float ScanRadius { get; init; } public float ScanCooldown { get; init; } public int ShieldHealth { get; init; } public float ShieldDuration { get; init; } // Consumable stats public int HealAmount { get; init; } public float ShieldBoostDuration { get; init; } public float DamageReduction { get; init; } public float SpeedBoostDuration { get; init; } public float SpeedMultiplier { get; init; } = 1f; // Armor stats public int HealthBonus { get; init; } public float SpeedPenalty { get; init; } public float DashDistance { get; init; } public float DashCooldown { get; init; } public static GameItemData FromEntity(GameItem e) => new() { Id = e.Id, Name = e.Name, Category = e.Category, CraftCost = e.CraftCost, Description = e.Description, LootValue = e.LootValue, Stackable = e.Stackable, Damage = e.Damage, FireRate = e.FireRate, ProjectileSpeed = e.ProjectileSpeed, Range = e.Range, AmmoType = e.AmmoType, PelletCount = e.PelletCount, Spread = e.Spread, ExplosionRadius = e.ExplosionRadius, HarvestMultiplier = e.HarvestMultiplier, ScanRadius = e.ScanRadius, ScanCooldown = e.ScanCooldown, ShieldHealth = e.ShieldHealth, ShieldDuration = e.ShieldDuration, HealAmount = e.HealAmount, ShieldBoostDuration = e.ShieldBoostDuration, DamageReduction = e.DamageReduction, SpeedBoostDuration = e.SpeedBoostDuration, SpeedMultiplier = e.SpeedMultiplier, HealthBonus = e.HealthBonus, SpeedPenalty = e.SpeedPenalty, DashDistance = e.DashDistance, DashCooldown = e.DashCooldown }; } /// /// Runtime recipe data (cached from database) /// public sealed class GameRecipeData { public int Id { get; init; } public int ResultItemId { get; init; } public int ScrapCost { get; init; } public int EnergyCost { get; init; } public int RareCost { get; init; } public bool CanCraft(int scrap, int energy, int rare) { return scrap >= ScrapCost && energy >= EnergyCost && rare >= RareCost; } public static GameRecipeData FromEntity(GameRecipe e) => new() { Id = e.Id, ResultItemId = e.ResultItemId, ScrapCost = e.ScrapCost, EnergyCost = e.EnergyCost, RareCost = e.RareCost }; } /// /// Cached item service that loads from database and refreshes periodically /// public sealed class CachedItemService : IItemService, IDisposable { private readonly ILogger _log; private readonly IServiceScopeFactory _scopeFactory; private readonly Timer _refreshTimer; private ConcurrentDictionary _items = new(); private ConcurrentDictionary _recipes = new(); private ConcurrentDictionary> _itemsByCategory = new(); private static readonly TimeSpan RefreshInterval = TimeSpan.FromMinutes(5); public CachedItemService(ILogger log, IServiceScopeFactory scopeFactory) { _log = log; _scopeFactory = scopeFactory; // Initial load _ = ReloadCacheAsync(); // Periodic refresh _refreshTimer = new Timer(_ => _ = ReloadCacheAsync(), null, RefreshInterval, RefreshInterval); } public GameItemData? GetItem(int id) => _items.TryGetValue(id, out var item) ? item : null; public GameRecipeData? GetRecipe(int id) => _recipes.TryGetValue(id, out var recipe) ? recipe : null; public IReadOnlyList GetAllItems() => _items.Values.ToList(); public IReadOnlyList GetAllRecipes() => _recipes.Values.ToList(); public IReadOnlyList GetItemsByCategory(ItemCategory category) { return _itemsByCategory.TryGetValue(category, out var items) ? items : new List(); } public async Task ReloadCacheAsync() { try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); // Load items var items = await db.GameItems .Where(i => i.IsEnabled) .ToListAsync(); var newItems = new ConcurrentDictionary(); var newByCategory = new ConcurrentDictionary>(); foreach (var item in items) { var data = GameItemData.FromEntity(item); newItems[item.Id] = data; if (!newByCategory.ContainsKey(item.Category)) newByCategory[item.Category] = new List(); newByCategory[item.Category].Add(data); } // Load recipes var recipes = await db.GameRecipes .Where(r => r.IsEnabled) .ToListAsync(); var newRecipes = new ConcurrentDictionary(); foreach (var recipe in recipes) { newRecipes[recipe.Id] = GameRecipeData.FromEntity(recipe); } // Atomic swap _items = newItems; _recipes = newRecipes; _itemsByCategory = newByCategory; _log.LogInformation("Loaded {ItemCount} items and {RecipeCount} recipes from database", items.Count, recipes.Count); } catch (Exception ex) { _log.LogError(ex, "Failed to reload item cache from database"); } } public void Dispose() { _refreshTimer.Dispose(); } } /// /// Fallback static item database (used if DB is empty or for seeding) /// public static class DefaultItemData { public static List GetDefaultItems() => new() { // Resources new() { Id = 1, Name = "Scrap Metal", Category = ItemCategory.Resource, CraftCost = 0, Description = "Basic salvage material", LootValue = 1, Stackable = true }, new() { Id = 2, Name = "Energy Cell", Category = ItemCategory.Resource, CraftCost = 0, Description = "Charged power source", LootValue = 2, Stackable = true }, new() { Id = 3, Name = "Rare Alloy", Category = ItemCategory.Resource, CraftCost = 0, Description = "Precious refined metal", LootValue = 5, Stackable = true }, // Weapons new() { Id = 100, Name = "Pulse Pistol", Category = ItemCategory.Weapon, CraftCost = 15, Description = "Basic sidearm", LootValue = 10, Stackable = false, Damage = 10, FireRate = 4f, ProjectileSpeed = 400f, Range = 300f }, new() { Id = 101, Name = "Scatter Gun", Category = ItemCategory.Weapon, CraftCost = 25, Description = "Close-range devastation", LootValue = 20, Stackable = false, Damage = 6, FireRate = 1.5f, ProjectileSpeed = 350f, Range = 150f, PelletCount = 5, Spread = 0.4f }, new() { Id = 102, Name = "Rail Rifle", Category = ItemCategory.Weapon, CraftCost = 40, Description = "Long-range precision", LootValue = 35, Stackable = false, Damage = 45, FireRate = 0.8f, ProjectileSpeed = 800f, Range = 600f }, new() { Id = 103, Name = "Plasma Launcher", Category = ItemCategory.Weapon, CraftCost = 60, Description = "Area damage weapon", LootValue = 50, Stackable = false, Damage = 30, FireRate = 0.5f, ProjectileSpeed = 250f, Range = 400f, ExplosionRadius = 50f }, // Tools new() { Id = 200, Name = "Mining Laser", Category = ItemCategory.Tool, CraftCost = 15, Description = "Harvests resources faster", LootValue = 12, Stackable = false, HarvestMultiplier = 2.0f }, new() { Id = 201, Name = "Scanner", Category = ItemCategory.Tool, CraftCost = 20, Description = "Reveals nearby resources and players", LootValue = 15, Stackable = false, ScanRadius = 200f, ScanCooldown = 10f }, new() { Id = 202, Name = "Portable Shield", Category = ItemCategory.Tool, CraftCost = 35, Description = "Deployable cover", LootValue = 25, Stackable = false, ShieldHealth = 100, ShieldDuration = 15f }, // Consumables new() { Id = 300, Name = "Repair Kit", Category = ItemCategory.Consumable, CraftCost = 10, Description = "Restores 30 health", LootValue = 8, Stackable = true, HealAmount = 30 }, new() { Id = 301, Name = "Shield Booster", Category = ItemCategory.Consumable, CraftCost = 15, Description = "Temporary damage reduction", LootValue = 12, Stackable = true, ShieldBoostDuration = 10f, DamageReduction = 0.3f }, new() { Id = 302, Name = "Speed Stim", Category = ItemCategory.Consumable, CraftCost = 12, Description = "Temporary speed boost", LootValue = 10, Stackable = true, SpeedBoostDuration = 8f, SpeedMultiplier = 1.5f }, // Armor new() { Id = 400, Name = "Light Suit", Category = ItemCategory.Armor, CraftCost = 20, Description = "+20 max health", LootValue = 15, Stackable = false, HealthBonus = 20 }, new() { Id = 401, Name = "Heavy Suit", Category = ItemCategory.Armor, CraftCost = 45, Description = "+50 max health, slower", LootValue = 35, Stackable = false, HealthBonus = 50, SpeedPenalty = 0.15f }, new() { Id = 402, Name = "Thruster Pack", Category = ItemCategory.Armor, CraftCost = 30, Description = "Dash ability", LootValue = 25, Stackable = false, DashDistance = 100f, DashCooldown = 5f } }; public static List GetDefaultRecipes() => new() { // Weapons new() { Id = 1, ResultItemId = 100, ScrapCost = 5, EnergyCost = 2, RareCost = 0 }, new() { Id = 2, ResultItemId = 101, ScrapCost = 8, EnergyCost = 3, RareCost = 0 }, new() { Id = 3, ResultItemId = 102, ScrapCost = 10, EnergyCost = 5, RareCost = 2 }, new() { Id = 4, ResultItemId = 103, ScrapCost = 15, EnergyCost = 8, RareCost = 4 }, // Tools new() { Id = 10, ResultItemId = 200, ScrapCost = 6, EnergyCost = 3, RareCost = 0 }, new() { Id = 11, ResultItemId = 201, ScrapCost = 8, EnergyCost = 4, RareCost = 1 }, new() { Id = 12, ResultItemId = 202, ScrapCost = 12, EnergyCost = 6, RareCost = 2 }, // Consumables new() { Id = 20, ResultItemId = 300, ScrapCost = 3, EnergyCost = 2, RareCost = 0 }, new() { Id = 21, ResultItemId = 301, ScrapCost = 4, EnergyCost = 3, RareCost = 0 }, new() { Id = 22, ResultItemId = 302, ScrapCost = 3, EnergyCost = 4, RareCost = 0 }, // Armor new() { Id = 30, ResultItemId = 400, ScrapCost = 8, EnergyCost = 0, RareCost = 1 }, new() { Id = 31, ResultItemId = 401, ScrapCost = 15, EnergyCost = 0, RareCost = 3 }, new() { Id = 32, ResultItemId = 402, ScrapCost = 10, EnergyCost = 5, RareCost = 2 } }; }