<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

/**
 * Centralized permission checking for integration routes.
 *
 * Eliminates duplicate logic between MenuGeneratorService, MenuCurrentUserPayloadService,
 * and any future consumers that need to evaluate route permission arrays.
 */
final class RoutePermissionChecker
{
    /**
     * Whether the current user can access a route with the given permissions list.
     *
     * Permission semantics:
     * - 'public'        → always accessible (short-circuits all other checks)
     * - 'authenticated' → requires logged-in user
     * - 'admin'         → requires manage_options capability
     * - anything else   → treated as a WordPress capability string
     *
     * All listed permissions must pass (AND logic), except 'public' which grants
     * immediate access regardless of other entries.
     *
     * @param array<string> $permissions
     */
    public static function canCurrentUserAccessRoute(array $permissions): bool
    {
        $allowed = true;
        if (!empty($permissions) && !\in_array('public', $permissions, true)) {
            foreach ($permissions as $permission) {
                if (!\is_string($permission) || !self::userSatisfiesPermission($permission)) {
                    $allowed = false;
                    break;
                }
            }
        }
        return $allowed;
    }

    private static function userSatisfiesPermission(string $permission): bool
    {
        $hasPermission = true;

        if ($permission === 'authenticated') {
            $hasPermission = \is_user_logged_in();
        } elseif ($permission === 'admin') {
            $hasPermission = \current_user_can('manage_options');
        } elseif ($permission !== 'public') {
            $hasPermission = \current_user_can($permission);
        }

        return $hasPermission;
    }
}
