Files
gameauthapi/Controllers/LocationController.cs
T

103 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
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 LocationController : ControllerBase
{
private readonly LocationService _locationService;
private readonly PlayerService _playerService;
public LocationController(LocationService locationService, PlayerService playerService)
{
_locationService = locationService;
_playerService = playerService;
}
[HttpPost]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Create([FromBody] CreateLocationRequest req)
{
var newLoc = new Location
{
X = req.X,
Y = req.Y,
Z = req.Z,
N = req.N,
NE = req.NE,
E = req.E,
SE = req.SE,
S = req.S,
SW = req.SW,
W = req.W,
NW = req.NW
};
await _locationService.CreateAsync(newLoc);
return Ok(newLoc);
}
[HttpPut("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Update(string id, [FromBody] UpdateLocationRequest req)
{
var location = await _locationService.GetByIdAsync(id);
if (location == null)
return NotFound("Location not found.");
location.X = req.X;
location.Y = req.Y;
location.Z = req.Z;
location.N = req.N;
location.NE = req.NE;
location.E = req.E;
location.SE = req.SE;
location.S = req.S;
location.SW = req.SW;
location.W = req.W;
location.NW = req.NW;
await _locationService.UpdateAsync(location);
return Ok(location);
}
[HttpDelete("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Delete(string id)
{
var location = await _locationService.GetByIdAsync(id);
if (location == null)
return NotFound("Location not found.");
// Null out all players at this location
var affectedPlayers = await _playerService.GetByLocationIdAsync(id);
foreach (var player in affectedPlayers)
{
player.LocationId = null;
await _playerService.UpdateAsync(player);
}
await _locationService.DeleteAsync(id);
return Ok($"Location deleted and {affectedPlayers.Count} player(s) unlinked.");
}
[HttpGet("{id}")]
[Authorize(Roles = "USER")]
public async Task<IActionResult> GetById(string id)
{
var location = await _locationService.GetByIdAsync(id);
if (location == null)
return NotFound("Location not found");
return Ok(location);
}
}