<?php
/**
 * 从所有角色中移除以下运维菜单及其按钮权限：
 * /safeguard/dict
 * /safeguard/attachment
 * /safeguard/database
 * /safeguard/server
 * /safeguard/cache
 * /safeguard/email-log
 *
 * 用法（在 server 目录）: php db/run_remove_safeguard_ops_role_menus.php
 */
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../support/bootstrap.php';

use plugin\saiadmin\app\cache\UserMenuCache;
use support\think\Db;

$targetRoutes = [
    '/safeguard/dict',
    '/safeguard/attachment',
    '/safeguard/database',
    '/safeguard/server',
    '/safeguard/cache',
    '/safeguard/email-log',
];

/**
 * @param int[] $parentIds
 * @return int[]
 */
function collectChildMenuIds(array $parentIds): array
{
    if ($parentIds === []) {
        return [];
    }

    $childIds = Db::name('sa_system_menu')
        ->whereIn('parent_id', $parentIds)
        ->column('id');

    if ($childIds === []) {
        return [];
    }

    $childIds = array_map('intval', $childIds);
    $deeper = collectChildMenuIds($childIds);

    return array_values(array_unique(array_merge($childIds, $deeper)));
}

echo "=== remove safeguard ops menus from all roles ===\n";

$rootMenuIds = Db::name('sa_system_menu')
    ->whereIn('component', $targetRoutes)
    ->column('id');

$rootMenuIds = array_map('intval', $rootMenuIds ?: []);
$childMenuIds = collectChildMenuIds($rootMenuIds);
$menuIds = array_values(array_unique(array_merge($rootMenuIds, $childMenuIds)));

if ($menuIds === []) {
    echo "WARN: no menu matched target routes\n";
    exit(0);
}

$menuRows = Db::name('sa_system_menu')
    ->whereIn('id', $menuIds)
    ->field('id, parent_id, name, component, slug, type')
    ->order('id', 'asc')
    ->select()
    ->toArray();

echo "Matched menus (" . count($menuRows) . "):\n";
foreach ($menuRows as $row) {
    echo sprintf(
        "  - id=%d parent=%d type=%s component=%s slug=%s name=%s\n",
        (int) ($row['id'] ?? 0),
        (int) ($row['parent_id'] ?? 0),
        (string) ($row['type'] ?? ''),
        (string) ($row['component'] ?? ''),
        (string) ($row['slug'] ?? ''),
        (string) ($row['name'] ?? '')
    );
}

$deleted = Db::name('sa_system_role_menu')->whereIn('menu_id', $menuIds)->delete();
echo "Deleted role-menu rows: {$deleted}\n";

$roleCount = Db::name('sa_system_role_menu')
    ->whereIn('menu_id', $menuIds)
    ->count();
echo "Remaining role-menu rows for these menus: {$roleCount}\n";

UserMenuCache::clearMenuCache();
echo "Cleared menu cache\n";

echo "Done.\n";
