<?php

namespace App\Support;

use App\Models\AdminRole;
use Illuminate\Support\Facades\DB;

final class InvalidPlatformAgentRoleCleanup
{
    public static function run(): int
    {
        $agentRoleId = DB::table('admin_roles')
            ->where('scope_type', AdminRole::SCOPE_SYSTEM)
            ->where('slug', PlatformSystemRoles::SLUG_AGENT)
            ->value('id');

        if ($agentRoleId === null) {
            return 0;
        }

        return DB::table('admin_user_site_roles')
            ->where('role_id', (int) $agentRoleId)
            ->whereNotExists(static function ($query): void {
                $query->selectRaw('1')
                    ->from('admin_user_agents as cleanup_uag')
                    ->join('agent_nodes as cleanup_node', 'cleanup_node.id', '=', 'cleanup_uag.agent_node_id')
                    ->whereColumn('cleanup_uag.admin_user_id', 'admin_user_site_roles.admin_user_id')
                    ->whereColumn('cleanup_node.admin_site_id', 'admin_user_site_roles.site_id');
            })
            ->delete();
    }
}
