Files
gameauthapi/Controllers/ItemController.cs
T

89 lines
2.8 KiB
C#

using System.Threading.Tasks;
using GameAuthApi.Models;
using GameAuthApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace GameAuthApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ItemController : ControllerBase
{
private readonly ItemService _itemService;
private readonly LocationService _locationService;
private readonly SpawnableService _spawnableService;
public ItemController(ItemService itemService, LocationService locationService, SpawnableService spawnableService)
{
_itemService = itemService;
_locationService = locationService;
_spawnableService = spawnableService;
}
[HttpPost]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Create([FromBody] CreateItemRequest req)
{
var location = await _locationService.GetByIdAsync(req.LocationId);
if (location == null)
return BadRequest("Invalid location ID.");
var uses = req.UsesRemaining;
var spawnable = await _spawnableService.GetByNameAsync(req.Name.ToLower());
if (spawnable != null && spawnable.Uses > 0)
uses = spawnable.Uses;
var item = new Item
{
Name = req.Name,
LocationId = req.LocationId,
UsesRemaining = uses
};
await _itemService.CreateAsync(item);
return Ok(item);
}
[HttpPut("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Update(string id, [FromBody] UpdateItemRequest req)
{
var item = await _itemService.GetByIdAsync(id);
if (item == null)
return NotFound("Item not found.");
var location = await _locationService.GetByIdAsync(req.LocationId);
if (location == null)
return BadRequest("Invalid location ID.");
if (item.LocationId != req.LocationId)
{
if (!string.IsNullOrEmpty(item.LocationId))
await _locationService.RemoveItemFromLocationAsync(item.LocationId, item.Id);
await _locationService.AddItemToLocationAsync(req.LocationId, item.Id);
}
item.Name = req.Name;
item.LocationId = req.LocationId;
item.UsesRemaining = req.UsesRemaining;
await _itemService.UpdateAsync(item);
return Ok(item);
}
[HttpDelete("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Delete(string id)
{
var item = await _itemService.GetByIdAsync(id);
if (item == null)
return NotFound("Item not found.");
if (!string.IsNullOrEmpty(item.LocationId))
await _locationService.RemoveItemFromLocationAsync(item.LocationId, item.Id);
await _itemService.DeleteAsync(id);
return Ok($"Item '{item.Name}' deleted.");
}
}