<?php

declare(strict_types=1);

namespace FleekDash\API;

use FleekDash\Admin\Menu\AdminMenuContextBuilder;

class MenuPhpMenuService
{
    public function __construct(
        private AdminMenuContextBuilder $adminMenuContextBuilder,
    ) {
    }

    /** @return array<string,mixed> */
    public function buildAuthDebugInfo(array $auth): array
    {
        $debug = [
            'error' => 'Not authenticated',
            'user_id' => \get_current_user_id(),
            'is_logged_in' => \is_user_logged_in(),
            'rest_request' => \defined('REST_REQUEST') && REST_REQUEST,
            'auth_result' => $auth,
        ];

        if (\defined('COOKIEHASH')) {
            $cookieName = 'wordpress_logged_in_' . COOKIEHASH;
            $debug['cookie_name'] = $cookieName;
            $debug['cookie_exists'] = isset($_COOKIE[$cookieName]);
            $debug['cookie_value_length'] = isset($_COOKIE[$cookieName]) ? \strlen($_COOKIE[$cookieName]) : 0;
        }

        if (\defined('COOKIEHASH') && isset($_COOKIE['wordpress_logged_in_' . COOKIEHASH])) {
            $validated = \wp_validate_auth_cookie('', 'logged_in');
            $debug['cookie_validation_result'] = $validated ? "User ID: {$validated}" : 'Failed';
        }

        return $debug;
    }

    /** @return array<int, array<string,mixed>> */
    public function getAdminMenuItems(): array
    {
        $this->adminMenuContextBuilder->ensureLoaded();
        $adminMenu = \FleekDash\Admin\AdminMenu::getInstance();
        if (!$adminMenu) {
            throw new MenuDataAPIException('AdminMenu::getInstance() returned null');
        }

        $items = $adminMenu->getAdminMenuItems();
        if (!\is_array($items)) {
            throw new MenuDataAPIException('AdminMenu::getAdminMenuItems() returned non-array: ' . \gettype($items));
        }

        return $items;
    }
}

