<?php

use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Support\AgentDefaultRolePermissions;
use App\Support\AgentPlatformRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        AgentDefaultRolePermissions::ensurePlatformAgentRole();
        $platformRoleId = AgentPlatformRole::id();

        foreach (DB::table('admin_user_agents')->get(['admin_user_id', 'agent_node_id']) as $binding) {
            $user = AdminUser::query()->find((int) $binding->admin_user_id);
            if ($user === null) {
                continue;
            }

            $user->syncPrimaryPlatformAgentRole((int) $binding->agent_node_id);
        }

        $ownerRoleIds = AdminRole::query()
            ->where('scope_type', AdminRole::SCOPE_AGENT)
            ->where('slug', 'like', 'agent_owner_%')
            ->pluck('id')
            ->all();

        if ($ownerRoleIds !== []) {
            DB::table('admin_user_agent_roles')->whereIn('role_id', $ownerRoleIds)->delete();
            DB::table('admin_user_site_roles')->whereIn('role_id', $ownerRoleIds)->delete();
            DB::table('admin_role_menu_actions')->whereIn('role_id', $ownerRoleIds)->delete();
            AdminRole::query()->whereIn('id', $ownerRoleIds)->delete();
        }
    }

    public function down(): void
    {
        // 不回滚：避免经营账号失权。
    }
};
