<?php

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

/**
 * 代理角色/账号 API 绑定到已有 agent.node.view / agent.node.manage 动作（同菜单下 action 唯一）。
 */
return new class extends Migration
{
    public function up(): void
    {
        $now = Carbon::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.agent-roles.')
                || str_starts_with((string) $resource['code'], 'admin.agent-admin-users.'),
        ));

        foreach ($resources as $resource) {
            $resourceId = DB::table('admin_api_resources')->where('code', $resource['code'])->value('id');
            $payload = [
                'module_code' => $resource['module_code'],
                'name' => $resource['name'],
                'http_method' => $resource['http_method'],
                'uri_pattern' => $resource['uri_pattern'],
                'route_name' => $resource['route_name'],
                'auth_mode' => $resource['auth_mode'],
                'is_audit_required' => $resource['is_audit_required'],
                'status' => 1,
                'meta_json' => null,
                'updated_at' => $now,
            ];

            if ($resourceId === null) {
                $resourceId = DB::table('admin_api_resources')->insertGetId($payload + [
                    'code' => $resource['code'],
                    'created_at' => $now,
                ]);
            } else {
                DB::table('admin_api_resources')->where('id', (int) $resourceId)->update($payload);
            }

            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,
                ]);
            }
        }

        if (! Schema::hasTable('admin_role_api_resources')) {
            return;
        }

        $superRoleId = DB::table('admin_roles')->where('slug', 'super_admin')->value('id');
        if ($superRoleId === null) {
            return;
        }

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

            DB::table('admin_role_api_resources')->updateOrInsert([
                'role_id' => (int) $superRoleId,
                'api_resource_id' => (int) $resourceId,
            ], []);
        }
    }

    public function down(): void
    {
        $codes = [
            'admin.agent-roles.update',
            'admin.agent-roles.destroy',
            'admin.agent-roles.permissions.sync',
            'admin.agent-roles.index',
            'admin.agent-roles.store',
            'admin.agent-admin-users.index',
            'admin.agent-admin-users.store',
            'admin.agent-admin-users.roles.sync',
        ];

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

            if (Schema::hasTable('admin_role_api_resources')) {
                DB::table('admin_role_api_resources')->where('api_resource_id', (int) $resourceId)->delete();
            }
            DB::table('admin_api_resource_bindings')->where('api_resource_id', (int) $resourceId)->delete();
            DB::table('admin_api_resources')->where('id', (int) $resourceId)->delete();
        }
    }
};
