using ERPCore.Domain.Entities;
using ERPCore.Dtos.Rbac;
using ERPCore.Repositories.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace ERPCore.Controllers;

/// <summary>
/// Read-only sidebar nav tree, used by the Role permission-assignment checkbox
/// UI and by `GET /auth/me` (see AuthController) to resolve a role's visible codes.
/// NavItem/SubNavItem rows are seeded (NavItemConfiguration/SubNavItemConfiguration)
/// to match the frontend's hardcoded sidebar — not admin-editable in this phase.
/// </summary>
[Route("api/v1/nav")]
public sealed class NavController : ApiControllerBase
{
    private readonly IRepository<NavItem> _navItems;

    public NavController(IRepository<NavItem> navItems) => _navItems = navItems;

    [HttpGet]
    [ProducesResponseType(typeof(List<NavItemDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<List<NavItemDto>>> GetTree(CancellationToken ct)
    {
        var items = await _navItems.Query().AsNoTracking()
            .Include(n => n.Children)
            .OrderBy(n => n.SortOrder)
            .ToListAsync(ct);

        var dto = items.Select(n => new NavItemDto(
            n.NavItemId, n.Code, n.Label, n.Icon, n.Href, n.SortOrder,
            n.Children.OrderBy(c => c.SortOrder)
                .Select(c => new SubNavItemDto(c.SubNavItemId, c.Code, c.Label, c.Icon, c.Href, c.SortOrder))
                .ToList())).ToList();

        return Ok(dto);
    }
}
