<?php

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use App\Support\AdminAuthorizationRegistry;
use Illuminate\Database\Migrations\Migration;

/**
 * 为已执行 140000 的环境补种 integration 权限动作并同步 API 绑定。
 */
return new class extends Migration
{
    public function up(): void
    {
        $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;
        }

        $configMenuId = DB::table('admin_menus')->where('code', 'config')->value('id');
        if ($configMenuId === null) {
            return;
        }

        $integrationMenuId = DB::table('admin_menus')->where('code', 'config.integration')->value('id');
        if ($integrationMenuId === null) {
            $integrationMenuId = DB::table('admin_menus')->insertGetId([
                'parent_id' => (int) $configMenuId,
                'menu_type' => 'page',
                'code' => 'config.integration',
                'name' => '主站接入站点',
                'path' => '/admin/config/integration-sites',
                'route_name' => 'admin.config.integration',
                'component' => 'config/integration',
                'icon' => null,
                'active_menu_code' => null,
                'sort_order' => 45,
                'is_visible' => true,
                'is_cache' => false,
                'is_external' => false,
                'status' => 1,
                'meta_json' => null,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        foreach ([
            ['permission_code' => 'integration.site.view', 'action_id' => (int) $viewActionId, 'name' => '接入站点查看'],
            ['permission_code' => 'integration.site.manage', 'action_id' => (int) $manageActionId, 'name' => '接入站点管理'],
        ] as $row) {
            if (DB::table('admin_menu_actions')->where('permission_code', $row['permission_code'])->exists()) {
                continue;
            }

            DB::table('admin_menu_actions')->insert([
                'menu_id' => (int) $integrationMenuId,
                'action_id' => $row['action_id'],
                'permission_code' => $row['permission_code'],
                'name' => $row['name'],
                'status' => 1,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        $menuActionIds = DB::table('admin_menu_actions')->pluck('id', 'permission_code');
        $resources = array_values(array_filter(
            AdminAuthorizationRegistry::resources(),
            static fn (array $resource): bool => str_starts_with((string) $resource['code'], 'admin.integration-sites.'),
        ));

        foreach ($resources as $resource) {
            $resourceId = DB::table('admin_api_resources')->where('code', $resource['code'])->value('id');
            if ($resourceId === null) {
                continue;
            }

            DB::table('admin_api_resource_bindings')
                ->where('api_resource_id', (int) $resourceId)
                ->delete();

            foreach ($resource['permission_codes'] as $permissionCode) {
                $menuActionId = $menuActionIds[$permissionCode] ?? null;
                if ($menuActionId === null) {
                    continue;
                }

                DB::table('admin_api_resource_bindings')->insert([
                    'api_resource_id' => (int) $resourceId,
                    'menu_action_id' => (int) $menuActionId,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }
    }

    public function down(): void
    {
        // 保留 menu_actions / bindings，避免回滚后超管无法管理已创建的接入站点。
    }
};
