<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

use FleekDash\API\MenuItemTransformHelper;
use FleekDash\API\MenuPayloadHash;
use FleekDash\Integration\RouteManager;

/**
 * Simplified menu pipeline for **debug / diagnostics only** ({@see \FleekDash\API\MenuDebugAPI}).
 *
 * **Not** the production menu for the React app:
 * - **GET /menu** uses {@see \FleekDash\API\MenuDataAPI::getMenu()} →
 *   {@see \FleekDash\API\MenuCurrentUserPayloadService::buildMenuItems()} (snapshot merge, core restore,
 *   integrations) then {@see \FleekDash\API\MenuRolePayloadService::applyRoleOverridesToMenuItems()}
 *   for the current user’s role.
 * - **GET /menu/{role}** (role preview / customization) uses {@see \FleekDash\API\MenuRolePayloadService}
 *   with capability-based formatter + role projection + overrides — not this class.
 *
 * This class only runs capture → {@see MenuItemFormatter} → backward-compat generator variant →
 * integrations, and does **not** apply stored role overrides or the full snapshot merge from MenuDataAPI.
 * Shared transforms live in {@see \FleekDash\API\MenuItemTransformHelper}.
 */
class MenuGeneratorService
{
    private MenuCaptureService $menuCapture;
    private MenuItemFormatter $menuFormatter;
    private RouteConverter $routeConverter;

    public function __construct(?MenuCaptureService $menuCapture = null, ?MenuItemFormatter $menuFormatter = null)
    {
        $this->routeConverter = new RouteConverter();
        $this->menuCapture = $menuCapture ?? new MenuCaptureService();
        $this->menuFormatter = $menuFormatter ?? new MenuItemFormatter($this->routeConverter);
    }

    /**
     * Generate menu for the current logged-in user.
     */
    public function generateForCurrentUser(): array
    {
        $userId = (int) \get_current_user_id();
        $pagenow = isset($GLOBALS['pagenow']) ? (string) $GLOBALS['pagenow'] : 'index.php';

        $this->menuCapture->ensureMenuCaptured();
        $menu = $this->menuCapture->getStoredMenu();
        $submenu = $this->menuCapture->getStoredSubmenu();

        $items = $this->menuFormatter->formatMenuItems($menu, $submenu);
        $items = MenuItemTransformHelper::applyBackwardCompatibilityGenerator($items);
        $items = $this->appendIntegrationRoutes($items);

        return $this->formatResponse($items, [
            'user_id' => $userId,
            'role' => $this->detectPrimaryRole($userId),
            'pagenow' => $pagenow,
            'raw_menu_count' => is_array($menu) ? count($menu) : 0,
            'raw_submenu_count' => is_array($submenu) ? count($submenu) : 0,
            'include_capabilities' => false,
            'source' => !empty($menu) ? $this->menuCapture->getLastSource() : 'missing',
        ]);
    }

    private function formatResponse(array $items, array $context): array
    {
        $meta = [
            'role' => $context['role'] ?? '',
            'user_id' => $context['user_id'] ?? \get_current_user_id(),
        ];

        if (!empty($context['include_capabilities'])) {
            $user = \get_userdata((int) $meta['user_id']);
            $meta['capabilities'] = $user ? array_keys($user->allcaps) : [];
        }

        return [
            'items' => $items,
            'menu_hash' => MenuPayloadHash::hashNormalizedMenu($items),
            'debug' => [
                'raw_menu_count' => $context['raw_menu_count'] ?? count($items),
                'raw_submenu_count' => $context['raw_submenu_count'] ?? 0,
                'formatted_count' => count($items),
                'wp_admin_defined' => defined('WP_ADMIN'),
                'pagenow' => $context['pagenow'] ?? 'index.php',
                'role' => $context['role'] ?? '',
                'user_id' => $context['user_id'] ?? \get_current_user_id(),
                'menu_source' => $context['source'] ?? 'unknown',
            ],
            'meta' => $meta,
        ];
    }

    private function detectPrimaryRole(int $userId): string
    {
        $user = \get_userdata($userId);
        if (!$user || empty($user->roles)) {
            return 'unknown';
        }

        return (string) $user->roles[0];
    }

    private function appendIntegrationRoutes(array $items): array
    {
        if (!class_exists(RouteManager::class)) {
            return $items;
        }

        $routes = RouteManager::getAll(true, true);
        if (empty($routes)) {
            return $items;
        }

        foreach ($routes as $route) {
            $type = $route['integration_type'] ?? '';

            if ($type !== 'standalone') {
                continue;
            }

            $permissions = $route['permissions'] ?? ['authenticated'];
            if (!RoutePermissionChecker::canCurrentUserAccessRoute($permissions)) {
                continue;
            }

            $items[] = MenuItemTransformHelper::convertIntegrationRouteToMenuItem($route);
        }

        usort($items, static function ($a, $b) {
            $posA = isset($a['position']) ? (float) $a['position'] : 0;
            $posB = isset($b['position']) ? (float) $b['position'] : 0;
            return $posA <=> $posB;
        });

        return $items;
    }

}
