<?php

namespace App\Support;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * 确保代理「角色 / 账号」拆分后的 menu_action 行存在（migrate 未跑或漏跑时 auth-sync 可补救）。
 */
final class AdminAgentPermissionMenuActionSync
{
    public static function syncMissing(): int
    {
        $now = Carbon::now();
        $viewActionId = DB::table('admin_action_catalog')->where('code', 'view')->value('id');
        $manageActionId = DB::table('admin_action_catalog')->where('code', 'manage')->value('id');
        if ($viewActionId === null || $manageActionId === null) {
            return 0;
        }

        $agentMenuId = (int) DB::table('admin_menus')->where('code', 'system.agents')->value('id');
        if ($agentMenuId === 0) {
            return 0;
        }

        $rolesMenuId = self::ensureChildMenu($agentMenuId, 'system.agents.roles', '代理角色', $now);
        $usersMenuId = self::ensureChildMenu($agentMenuId, 'system.agents.users', '代理账号', $now);

        $created = 0;
        $created += self::ensureMenuAction((int) $rolesMenuId, (int) $viewActionId, 'agent.role.view', '代理角色查看', $now) ? 1 : 0;
        $created += self::ensureMenuAction((int) $rolesMenuId, (int) $manageActionId, 'agent.role.manage', '代理角色管理', $now) ? 1 : 0;
        $created += self::ensureMenuAction((int) $usersMenuId, (int) $viewActionId, 'agent.user.view', '代理账号查看', $now) ? 1 : 0;
        $created += self::ensureMenuAction((int) $usersMenuId, (int) $manageActionId, 'agent.user.manage', '代理账号管理', $now) ? 1 : 0;

        return $created;
    }

    private static function ensureChildMenu(int $parentId, string $code, string $name, Carbon $now): int
    {
        $existing = DB::table('admin_menus')->where('code', $code)->value('id');
        if ($existing !== null) {
            return (int) $existing;
        }

        return (int) DB::table('admin_menus')->insertGetId([
            'parent_id' => $parentId,
            'menu_type' => 'button',
            'code' => $code,
            'name' => $name,
            'path' => null,
            'route_name' => null,
            'component' => null,
            'icon' => null,
            'active_menu_code' => 'system.agents',
            'sort_order' => 0,
            'is_visible' => false,
            'is_cache' => false,
            'is_external' => false,
            'status' => 1,
            'meta_json' => null,
            'created_at' => $now,
            'updated_at' => $now,
        ]);
    }

    private static function ensureMenuAction(int $menuId, int $actionId, string $permissionCode, string $name, Carbon $now): bool
    {
        if (DB::table('admin_menu_actions')->where('permission_code', $permissionCode)->exists()) {
            return false;
        }

        DB::table('admin_menu_actions')->insert([
            'menu_id' => $menuId,
            'action_id' => $actionId,
            'permission_code' => $permissionCode,
            'name' => $name,
            'status' => 1,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        return true;
    }
}
