using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Server.Data; using Server.Services.Auth; using VoidScavengers.Game; namespace VoidScavengers.Api; /// /// API endpoints for game items and recipes /// [ApiController] [Route("api/items")] public class ItemsController : ControllerBase { private readonly GameDbContext _db; private readonly IItemService _itemService; private readonly IAdminAuthService _adminAuth; public ItemsController(GameDbContext db, IItemService itemService, IAdminAuthService adminAuth) { _db = db; _itemService = itemService; _adminAuth = adminAuth; } /// /// Get all items (from cache) - public endpoint /// [HttpGet] public IActionResult GetAllItems([FromQuery] ItemCategory? category = null) { var items = category.HasValue ? _itemService.GetItemsByCategory(category.Value) : _itemService.GetAllItems(); return Ok(items); } /// /// Get a specific item - public endpoint /// [HttpGet("{id}")] public IActionResult GetItem(int id) { var item = _itemService.GetItem(id); if (item == null) return NotFound(new { error = "Item not found" }); return Ok(item); } /// /// Get all recipes (from cache) - public endpoint /// [HttpGet("recipes")] public IActionResult GetAllRecipes() { var recipes = _itemService.GetAllRecipes(); // Enrich with item names var enriched = recipes.Select(r => new { r.Id, r.ResultItemId, ResultItemName = _itemService.GetItem(r.ResultItemId)?.Name ?? "Unknown", r.ScrapCost, r.EnergyCost, r.RareCost }); return Ok(enriched); } /// /// Force reload the item cache (admin only) /// [HttpPost("reload")] public async Task ReloadCache() { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); await _itemService.ReloadCacheAsync(); return Ok(new { message = "Cache reloaded", itemCount = _itemService.GetAllItems().Count }); } /// /// Create or update an item (admin only) /// [HttpPost] public async Task UpsertItem([FromBody] GameItemDto dto) { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); var existing = await _db.GameItems.FindAsync(dto.Id); if (existing == null) { var item = new GameItem { Id = dto.Id, Name = dto.Name, Category = dto.Category, CraftCost = dto.CraftCost, Description = dto.Description, LootValue = dto.LootValue, Stackable = dto.Stackable, IsEnabled = dto.IsEnabled, Damage = dto.Damage, FireRate = dto.FireRate, ProjectileSpeed = dto.ProjectileSpeed, Range = dto.Range, AmmoType = dto.AmmoType, PelletCount = dto.PelletCount, Spread = dto.Spread, ExplosionRadius = dto.ExplosionRadius, HarvestMultiplier = dto.HarvestMultiplier, ScanRadius = dto.ScanRadius, ScanCooldown = dto.ScanCooldown, ShieldHealth = dto.ShieldHealth, ShieldDuration = dto.ShieldDuration, HealAmount = dto.HealAmount, ShieldBoostDuration = dto.ShieldBoostDuration, DamageReduction = dto.DamageReduction, SpeedBoostDuration = dto.SpeedBoostDuration, SpeedMultiplier = dto.SpeedMultiplier, HealthBonus = dto.HealthBonus, SpeedPenalty = dto.SpeedPenalty, DashDistance = dto.DashDistance, DashCooldown = dto.DashCooldown, CreatedAt = DateTime.UtcNow }; _db.GameItems.Add(item); } else { existing.Name = dto.Name; existing.Category = dto.Category; existing.CraftCost = dto.CraftCost; existing.Description = dto.Description; existing.LootValue = dto.LootValue; existing.Stackable = dto.Stackable; existing.IsEnabled = dto.IsEnabled; existing.Damage = dto.Damage; existing.FireRate = dto.FireRate; existing.ProjectileSpeed = dto.ProjectileSpeed; existing.Range = dto.Range; existing.AmmoType = dto.AmmoType; existing.PelletCount = dto.PelletCount; existing.Spread = dto.Spread; existing.ExplosionRadius = dto.ExplosionRadius; existing.HarvestMultiplier = dto.HarvestMultiplier; existing.ScanRadius = dto.ScanRadius; existing.ScanCooldown = dto.ScanCooldown; existing.ShieldHealth = dto.ShieldHealth; existing.ShieldDuration = dto.ShieldDuration; existing.HealAmount = dto.HealAmount; existing.ShieldBoostDuration = dto.ShieldBoostDuration; existing.DamageReduction = dto.DamageReduction; existing.SpeedBoostDuration = dto.SpeedBoostDuration; existing.SpeedMultiplier = dto.SpeedMultiplier; existing.HealthBonus = dto.HealthBonus; existing.SpeedPenalty = dto.SpeedPenalty; existing.DashDistance = dto.DashDistance; existing.DashCooldown = dto.DashCooldown; } await _db.SaveChangesAsync(); await _itemService.ReloadCacheAsync(); return Ok(new { message = existing == null ? "Item created" : "Item updated", id = dto.Id }); } /// /// Create or update a recipe (admin only) /// [HttpPost("recipes")] public async Task UpsertRecipe([FromBody] GameRecipeDto dto) { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); var existing = await _db.GameRecipes.FindAsync(dto.Id); if (existing == null) { var recipe = new GameRecipe { Id = dto.Id, ResultItemId = dto.ResultItemId, ScrapCost = dto.ScrapCost, EnergyCost = dto.EnergyCost, RareCost = dto.RareCost, IsEnabled = dto.IsEnabled, CreatedAt = DateTime.UtcNow }; _db.GameRecipes.Add(recipe); } else { existing.ResultItemId = dto.ResultItemId; existing.ScrapCost = dto.ScrapCost; existing.EnergyCost = dto.EnergyCost; existing.RareCost = dto.RareCost; existing.IsEnabled = dto.IsEnabled; } await _db.SaveChangesAsync(); await _itemService.ReloadCacheAsync(); return Ok(new { message = existing == null ? "Recipe created" : "Recipe updated", id = dto.Id }); } /// /// Seed default items if database is empty (admin only) /// [HttpPost("seed")] public async Task SeedDefaults() { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); var existingItemCount = await _db.GameItems.CountAsync(); var existingRecipeCount = await _db.GameRecipes.CountAsync(); if (existingItemCount > 0 || existingRecipeCount > 0) return BadRequest(new { error = "Database already has items/recipes. Clear first or use upsert." }); var defaultItems = DefaultItemData.GetDefaultItems(); var defaultRecipes = DefaultItemData.GetDefaultRecipes(); _db.GameItems.AddRange(defaultItems); _db.GameRecipes.AddRange(defaultRecipes); await _db.SaveChangesAsync(); await _itemService.ReloadCacheAsync(); return Ok(new { message = "Default items seeded", itemsAdded = defaultItems.Count, recipesAdded = defaultRecipes.Count }); } /// /// Delete an item (admin only) /// [HttpDelete("{id}")] public async Task DeleteItem(int id) { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); var item = await _db.GameItems.FindAsync(id); if (item == null) return NotFound(new { error = "Item not found" }); _db.GameItems.Remove(item); await _db.SaveChangesAsync(); await _itemService.ReloadCacheAsync(); return Ok(new { message = "Item deleted", id }); } /// /// Delete a recipe (admin only) /// [HttpDelete("recipes/{id}")] public async Task DeleteRecipe(int id) { var auth = await ValidateAdminAsync(); if (!auth.IsAuthorized) return Unauthorized(new { error = auth.Error }); var recipe = await _db.GameRecipes.FindAsync(id); if (recipe == null) return NotFound(new { error = "Recipe not found" }); _db.GameRecipes.Remove(recipe); await _db.SaveChangesAsync(); await _itemService.ReloadCacheAsync(); return Ok(new { message = "Recipe deleted", id }); } private async Task ValidateAdminAsync() { var token = Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", ""); return await _adminAuth.ValidateAsync(token, AccountRole.Admin); } } public class GameItemDto { public int Id { get; set; } public string Name { get; set; } = ""; public ItemCategory Category { get; set; } public int CraftCost { get; set; } public string Description { get; set; } = ""; public int LootValue { get; set; } public bool Stackable { get; set; } public bool IsEnabled { get; set; } = true; public int Damage { get; set; } public float FireRate { get; set; } public float ProjectileSpeed { get; set; } public float Range { get; set; } public int AmmoType { get; set; } public int PelletCount { get; set; } = 1; public float Spread { get; set; } public float ExplosionRadius { get; set; } public float HarvestMultiplier { get; set; } = 1f; public float ScanRadius { get; set; } public float ScanCooldown { get; set; } public int ShieldHealth { get; set; } public float ShieldDuration { get; set; } public int HealAmount { get; set; } public float ShieldBoostDuration { get; set; } public float DamageReduction { get; set; } public float SpeedBoostDuration { get; set; } public float SpeedMultiplier { get; set; } = 1f; public int HealthBonus { get; set; } public float SpeedPenalty { get; set; } public float DashDistance { get; set; } public float DashCooldown { get; set; } } public class GameRecipeDto { public int Id { get; set; } public int ResultItemId { get; set; } public int ScrapCost { get; set; } public int EnergyCost { get; set; } public int RareCost { get; set; } public bool IsEnabled { get; set; } = true; }