93 lines
2.6 KiB
C#
93 lines
2.6 KiB
C#
using LocationsApi.Models;
|
|
using LocationsApi.Services;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Security.Claims;
|
|
|
|
namespace LocationsApi.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class UnitsController : ControllerBase
|
|
{
|
|
private readonly UnitTrainingService _units;
|
|
|
|
public UnitsController(UnitTrainingService units)
|
|
{
|
|
_units = units;
|
|
}
|
|
|
|
[Authorize(Roles = "USER,SUPER")]
|
|
[HttpGet("me")]
|
|
public async Task<ActionResult<PlayerUnitsResponse>> GetMine()
|
|
{
|
|
var username = User.FindFirstValue(ClaimTypes.Name);
|
|
if (string.IsNullOrWhiteSpace(username))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
return Ok(await _units.GetMineAsync(username));
|
|
}
|
|
|
|
[Authorize(Roles = "USER,SUPER")]
|
|
[HttpPost("train")]
|
|
public async Task<ActionResult<UnitTrainingResponse>> Train([FromBody] TrainUnitRequest request)
|
|
{
|
|
var username = User.FindFirstValue(ClaimTypes.Name);
|
|
if (string.IsNullOrWhiteSpace(username))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
try
|
|
{
|
|
var training = await _units.TrainAsync(username, request);
|
|
if (training is null)
|
|
{
|
|
return BadRequest(new { error = "Not enough resources." });
|
|
}
|
|
|
|
return Ok(UnitTrainingResponse.FromTraining(training));
|
|
}
|
|
catch (ArgumentException ex)
|
|
{
|
|
return BadRequest(new { error = ex.Message });
|
|
}
|
|
catch (InvalidOperationException ex)
|
|
{
|
|
return BadRequest(new { error = ex.Message });
|
|
}
|
|
}
|
|
|
|
[Authorize(Roles = "USER,SUPER")]
|
|
[HttpPost("move")]
|
|
public async Task<ActionResult<List<UnitInstanceResponse>>> Move([FromBody] MoveUnitSquadRequest request)
|
|
{
|
|
var username = User.FindFirstValue(ClaimTypes.Name);
|
|
if (string.IsNullOrWhiteSpace(username))
|
|
{
|
|
return Unauthorized();
|
|
}
|
|
|
|
try
|
|
{
|
|
var units = await _units.MoveSquadAsync(username, request);
|
|
if (units.Count == 0)
|
|
{
|
|
return BadRequest(new { error = "No matching units are available to move." });
|
|
}
|
|
|
|
return Ok(units.Select(UnitInstanceResponse.FromUnit).ToList());
|
|
}
|
|
catch (ArgumentException ex)
|
|
{
|
|
return BadRequest(new { error = ex.Message });
|
|
}
|
|
catch (InvalidOperationException ex)
|
|
{
|
|
return BadRequest(new { error = ex.Message });
|
|
}
|
|
}
|
|
}
|