63 lines
1.7 KiB
C#
63 lines
1.7 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.UnitType);
|
|
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 });
|
|
}
|
|
}
|
|
}
|