using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SolutionErp.Application.Permissions;
using SolutionErp.Application.Permissions.Dtos;

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/roles")]
[Authorize]
public class RolesController(IMediator mediator) : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<List<RoleDto>>> List(CancellationToken ct)
        => Ok(await mediator.Send(new ListRolesQuery(), ct));

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Create([FromBody] CreateRoleCommand body, CancellationToken ct)
    {
        var id = await mediator.Send(body, ct);
        return CreatedAtAction(nameof(List), new { id }, new { id });
    }

    [HttpPut("{id:guid}")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateRoleCommand body, CancellationToken ct)
    {
        if (id != body.Id) return BadRequest("Id mismatch");
        await mediator.Send(body, ct);
        return NoContent();
    }

    [HttpDelete("{id:guid}")]
    [Authorize(Roles = "Admin")]
    public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
    {
        await mediator.Send(new DeleteRoleCommand(id), ct);
        return NoContent();
    }
}
