using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ROLAC.API.Authorization;
using ROLAC.API.DTOs.Permissions;
using ROLAC.API.Services;

namespace ROLAC.API.Controllers;

/// <summary>
/// Admin surface for the configurable RBAC matrix. Restricted to super_admin —
/// the role that governs who governs everyone else.
/// </summary>
[ApiController]
[Route("api/permissions")]
[Authorize(Roles = "super_admin")]
public class PermissionsController : ControllerBase
{
    private readonly IPermissionService _permissions;
    public PermissionsController(IPermissionService permissions) => _permissions = permissions;

    /// <summary>GET /api/permissions — the full role × module matrix.</summary>
    [HttpGet]
    public async Task<IActionResult> GetMatrix() => Ok(await _permissions.GetMatrixAsync());

    /// <summary>GET /api/permissions/catalog — module + action names for the grid.</summary>
    [HttpGet("catalog")]
    public IActionResult GetCatalog() => Ok(new PermissionCatalogDto
    {
        Modules = Modules.All,
        Actions = PermissionActions.All,
    });

    /// <summary>PUT /api/permissions/{roleName} — replaces a role's grants.</summary>
    [HttpPut("{roleName}")]
    public async Task<IActionResult> UpdateRole(string roleName, [FromBody] UpdateRolePermissionsRequest request)
    {
        try
        {
            await _permissions.UpsertRoleAsync(roleName, request.Modules);
            return NoContent();
        }
        catch (KeyNotFoundException)         { return NotFound(); }
        catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
    }
}
