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

namespace SolutionErp.Api.Controllers;

[ApiController]
[Route("api/menus")]
[Authorize]
public class MenusController(IMediator mediator) : ControllerBase
{
    [HttpGet("me")]
    public async Task<ActionResult<List<MenuNodeDto>>> Me(CancellationToken ct)
        => Ok(await mediator.Send(new GetMyMenuTreeQuery(), ct));

    [HttpGet]
    public async Task<ActionResult<List<MenuItemDto>>> List(CancellationToken ct)
        => Ok(await mediator.Send(new ListMenuItemsQuery(), ct));

    // [Mig 27] Admin Ẩn/Hiện + Đổi tên hiển thị menu cho fe-user. Body shape khớp
    // UpdateMenuItemCommand. Authorize policy "Permissions.Update" (admin matrix
    // quản lý phân quyền — cùng scope).
    public record UpdateMenuItemRequest(bool IsVisible, string? DisplayLabel);

    [HttpPatch("{key}")]
    [Authorize(Policy = "Permissions.Update")]
    public async Task<IActionResult> Update(string key, [FromBody] UpdateMenuItemRequest body, CancellationToken ct)
    {
        await mediator.Send(new UpdateMenuItemCommand(key, body.IsVisible, body.DisplayLabel), ct);
        return NoContent();
    }
}
