<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

use FleekDash\API\MenuPayloadHash;

/**
 * Menu Role Request Handler
 *
 * Handles menu resolution for role-specific requests.
 * Delegates to AdminMenu or MenuCaptureService with fallback.
 *
 * @package FleekDash\Admin\Menu
 */
class MenuRoleRequestHandler
{
    public function __construct(
        private MenuSourceResolver $menuSourceResolver,
        private $formatAndEnrichFromRaw,
    ) {
    }

    /**
     * @return array{items: array<int, array<string,mixed>>, source: string, raw_menu_count: int, raw_submenu_count: int}
     */
    public function getRoleMenuItemsWithSource(): array
    {
        [$menu, $submenu, $source] = $this->menuSourceResolver->resolve();
        $menu_items = [];
        if (!empty($menu) && \is_array($menu)) {
            $menu_items = ($this->formatAndEnrichFromRaw)($menu, $submenu);
        }

        return [
            'items' => \is_array($menu_items) ? $menu_items : [],
            'source' => $source,
            'raw_menu_count' => \is_array($menu) ? \count($menu) : 0,
            'raw_submenu_count' => \is_array($submenu) ? \count($submenu) : 0,
        ];
    }

    /**
     * @param array{items: array<int, array<string,mixed>>, source: string, raw_menu_count: int, raw_submenu_count: int} $resolved
     * @param mixed $role
     * @return array<string,mixed>
     */
    public function buildRoleMenuPayload(array $resolved, $role, int $user_id): array
    {
        $menu_items = $resolved['items'];
        return [
            'items' => $menu_items,
            'menu_hash' => MenuPayloadHash::hashNormalizedMenu($menu_items), // NOSONAR - Content hash for change detection, not security
            'meta' => ['role' => $role, 'user_id' => $user_id],
            'debug' => [
                'source' => $resolved['source'],
                'raw_menu_count' => $resolved['raw_menu_count'],
                'raw_submenu_count' => $resolved['raw_submenu_count'],
                'formatted_count' => \count($menu_items),
            ],
        ];
    }
}
