<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

final class MenuSnapshotRebuildService
{
    public function __construct(
        private AdminMenuContextBuilder $contextBuilder = new AdminMenuContextBuilder(),
        private MenuCaptureService $captureService = new MenuCaptureService(),
    ) {
    }

    public function rebuildForCurrentUser(): void
    {
        $userId = (int) \get_current_user_id();
        if ($userId <= 0) {
            return;
        }

        $this->contextBuilder->ensureLoaded();

        global $menu, $submenu;
        if (empty($menu) || !\is_array($menu)) {
            return;
        }

        $submenuArray = \is_array($submenu) ? $submenu : [];
        if (!$this->shouldPersistSnapshot($submenuArray)) {
            if (\defined('WP_DEBUG') && WP_DEBUG) {
                \error_log('[FleekDash MenuSnapshotRebuildService] Skipping persist: snapshot failed quality gate (sparse core submenus).');
            }
            return;
        }

        $this->captureService->clearInMemoryCache();
        $this->captureService->captureAdminMenu($menu, $submenuArray);
        $this->captureService->persistSnapshotForCurrentUser();
    }

    /**
     * Avoid overwriting a healthy wp-admin snapshot with a thin REST build (e.g. edit.php with one row).
     */
    private function shouldPersistSnapshot(array $submenu): bool
    {
        $editRows = isset($submenu['edit.php']) && \is_array($submenu['edit.php'])
            ? \count($submenu['edit.php'])
            : 0;
        $themesRows = isset($submenu['themes.php']) && \is_array($submenu['themes.php'])
            ? \count($submenu['themes.php'])
            : 0;

        return $editRows >= 2 || $themesRows >= 1;
    }
}

