<?php

declare(strict_types=1);

namespace apexl\Io\modules\menu\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\interfaces\OutputManagerInterface;
use apexl\Io\modules\menu\services\MenuManager;
use apexl\Io\modules\user\services\CurrentUserFactory;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Phase 5 (quiet mode) support — exposes the current user's permission-
 * gated top-level nav groups as a flat catalogue, WITHOUT any
 * NavFilterInterface narrowing applied (`applyNavFilters: false`).
 *
 * This is the seam a nav-allowlist picker (workspace admin checklist,
 * per-user "Simplify my navigation" picker) builds its options from — it
 * needs to offer every group the viewer could POSSIBLY see, not the
 * already-narrowed set. io-menu owns menu structure, so it owns this
 * catalogue; consumers (e.g. `apexl/io-page-layouts`) only ever deal in
 * the plain route-name strings this returns.
 */
final readonly class NavGroupsController extends Controller
{
    public function __construct(
        private CurrentUserFactory $currentUserFactory,
        private MenuManager        $menuManager,
        OutputManagerInterface     $output,
    ) {
        parent::__construct($output);
    }

    /**
     * GET /api/v1/menu/nav-groups?menu=navigation
     *
     * Response: { groups: [{ name, title, icon }, ...] }
     *
     * `name` is the dot-normalised routeName menuItem::$name carries —
     * the same string a NavFilterInterface allowlist matches against and
     * therefore the value allowlist pickers must store/send back.
     */
    public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $user = $this->currentUserFactory->get();
        if (!$user?->id) {
            return $this->json($response, ['error' => 'Not authenticated'], 401);
        }

        $params   = $request->getQueryParams();
        $menuName = (string) ($params['menu'] ?? 'navigation');

        $items = $this->menuManager->getAllItemsAsMenu(
            $user,
            $menuName,
            filterByPermission: true,
            applyNavFilters: false,
        );

        $groups = [];
        foreach ($items as $item) {
            if (!isset($item->name)) {
                continue;
            }
            $groups[] = [
                'name'  => (string) $item->name,
                'title' => (string) ($item->title ?? $item->name),
                'icon'  => isset($item->icon) && $item->icon !== '' ? (string) $item->icon : null,
            ];
        }

        return $this->json($response, ['groups' => $groups]);
    }
}
