<?php

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

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

        AgentNode::query()->each(static function (AgentNode $node): void {
            $ownerRole = AdminRole::query()
                ->where('owner_agent_id', $node->id)
                ->where('slug', 'agent_owner_'.$node->id)
                ->first();

            if ($ownerRole !== null) {
                $ownerRole->syncLegacyPermissionSlugs(AgentDefaultRolePermissions::ownerSlugsForNode($node));
            }
        });

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

            $agentRoleIds = DB::table('admin_user_agent_roles')
                ->where('admin_user_id', $adminUserId)
                ->where('agent_node_id', $agentNodeId)
                ->pluck('role_id')
                ->map(static fn ($id): int => (int) $id)
                ->all();

            if ($agentRoleIds === []) {
                $ownerId = (int) (AdminRole::query()
                    ->where('owner_agent_id', $agentNodeId)
                    ->where('slug', 'agent_owner_'.$agentNodeId)
                    ->value('id') ?? 0);
                if ($ownerId > 0) {
                    $agentRoleIds = [$ownerId];
                }
            }

            if ($agentRoleIds !== []) {
                $user->syncAgentRoleIds($agentNodeId, $agentRoleIds);
            }
        }
    }

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