80 lines
2.4 KiB
C#
80 lines
2.4 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;
|
|
|
|
public ItemController(ItemService itemService, LocationService locationService)
|
|
{
|
|
_itemService = itemService;
|
|
_locationService = locationService;
|
|
}
|
|
|
|
[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 item = new Item
|
|
{
|
|
Name = req.Name,
|
|
LocationId = req.LocationId
|
|
};
|
|
|
|
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;
|
|
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.");
|
|
}
|
|
}
|