<?php

namespace App\Http\Controllers\Api\V1\Admin\Agent;

use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminAgentNodeAccess;
use App\Support\AdminAgentScope;
use App\Support\AgentNodePresenter;

final class AgentNodeTreeController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $siteId = AdminAgentNodeAccess::resolveAdminSiteId(
            $admin,
            $request->integer('admin_site_id') ?: null,
        );

        $denied = AdminAgentNodeAccess::denyUnlessSiteResolved($admin, $siteId);
        if ($denied !== null) {
            return $denied;
        }

        $nodes = AdminAgentScope::visibleNodesQuery($admin, (int) $siteId)->get();

        return ApiResponse::success([
            'admin_site_id' => (int) $siteId,
            'tree' => AgentNodePresenter::tree($nodes),
        ]);
    }
}
