<?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\AdminAgentScope;
use App\Support\AgentNodePresenter;
use App\Models\AgentNode;

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

        $query = AgentNode::query()->orderBy('admin_site_id')->orderBy('path');

        if (! $admin->isSuperAdmin()) {
            $actor = AdminAgentScope::primaryAgentNode($admin);
            if ($actor === null) {
                $query->whereRaw('0 = 1');
            } else {
                $query
                    ->where('admin_site_id', (int) $actor->admin_site_id)
                    ->where('path', 'like', $actor->path.'%');
            }
        }

        return ApiResponse::success([
            'admin_site_id' => null,
            'items' => AgentNodePresenter::list($query->get()),
        ]);
    }
}
