<?php

declare(strict_types=1);

namespace FleekDash\API;

/**
 * Shared menu item transforms used by MenuDataAPI, MenuGeneratorService, and menu payload services.
 *
 * Note: {@see AdminDataFormatter::addBackwardCompatibility()} is a separate recursive/conditional variant
 * for other API surfaces; do not replace it without auditing consumers.
 */
final class MenuItemTransformHelper
{
    /**
     * @param array<int, array<string, mixed>> $items
     * @return array<int, array<string, mixed>>
     */
    public static function sortMenuItemsByPosition(array $items): array
    {
        \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;
    }

    /**
     * Standalone integration route → formatted top-level menu item (React app routes).
     *
     * @param array<string, mixed> $route Route row from RouteManager::getAll()
     * @return array<string, mixed>
     */
    public static function convertIntegrationRouteToMenuItem(array $route): array
    {
        $cleanPath = \trim((string) ($route['route_path'] ?? ''), '/');
        $reactPath = 'app/' . $cleanPath;
        $baseUrl = \admin_url('admin.php?page=fleekdash');
        $menuOrder = isset($route['menu_order']) ? (int) $route['menu_order'] : 0;
        $position = 200 + $menuOrder;

        $name = $route['route_title'] ?? $route['integration_name'] ?? $cleanPath;
        $icon = $route['icon'] ?? 'sparkles';
        $uniqueId = \sprintf(
            'integration_%s_%s',
            $route['integration_id'],
            \str_replace('/', '_', $cleanPath)
        );

        return [
            'name' => $name,
            'href' => $reactPath,
            'icon' => $icon,
            'capability' => 'read',
            'url' => $baseUrl . '#/' . $reactPath,
            'position' => $position,
            'order' => $position,
            'update_count' => 0,
            'is_wp_native' => false,
            'route_type' => 'react',
            'target' => '_self',
            'id' => $uniqueId,
            'unique_id' => $uniqueId,
            'integration_id' => $route['integration_id'],
            'integration_type' => $route['integration_type'],
        ];
    }

    /**
     * Aliases used by REST menu payload builders ({@see MenuCurrentUserPayloadService}, {@see MenuRolePayloadService}).
     *
     * @param array<int, array<string, mixed>> $items
     * @return array<int, array<string, mixed>>
     */
    public static function applyBackwardCompatibilityPayload(array $items): array
    {
        foreach ($items as &$item) {
            $item['title'] = $item['name'] ?? '';
            $item['id'] = $item['unique_id'] ?? ($item['id'] ?? '');

            if (isset($item['submenu']) && \is_array($item['submenu'])) {
                foreach ($item['submenu'] as &$subitem) {
                    $subitem['title'] = $subitem['name'] ?? '';
                    $subitem['id'] = $subitem['unique_id'] ?? ($subitem['id'] ?? '');
                }
            }
        }

        return $items;
    }

    /**
     * Aliases + default icon for snapshot-based {@see MenuGeneratorService} output.
     *
     * @param array<int, array<string, mixed>> $items
     * @return array<int, array<string, mixed>>
     */
    public static function applyBackwardCompatibilityGenerator(array $items): array
    {
        foreach ($items as &$item) {
            $item['title'] = $item['name'];
            $item['id'] = $item['unique_id'];

            if (!isset($item['icon'])) {
                $item['icon'] = 'dashicons-admin-generic';
            }

            if (isset($item['submenu']) && \is_array($item['submenu'])) {
                foreach ($item['submenu'] as &$subitem) {
                    $subitem['title'] = $subitem['name'];
                    $subitem['id'] = $subitem['unique_id'];

                    if (!isset($subitem['icon'])) {
                        $subitem['icon'] = 'dashicons-admin-generic';
                    }
                }
            }
        }

        return $items;
    }
}
