<?php

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

use App\Http\Controllers\Controller;
use App\Models\AdminSite;
use App\Models\AgentNode;
use App\Support\AdminIntegrationSitePresenter;
use App\Support\AdminSiteScope;
use App\Support\AgentLinePresenter;
use App\Support\AgentNodePresenter;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/** GET /api/v1/admin/agent-lines/{admin_site} */
final class AgentLineShowController extends Controller
{
    public function __invoke(Request $request, AdminSite $admin_site): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        if (! AdminSiteScope::siteIdAllowed($admin, (int) $admin_site->id)) {
            abort(403);
        }

        $root = AgentNode::query()
            ->where('admin_site_id', $admin_site->id)
            ->where('depth', 0)
            ->firstOrFail();

        return ApiResponse::success([
            'site' => AdminIntegrationSitePresenter::detail($admin_site),
            'agent_node' => AgentNodePresenter::item($root),
            'line_root' => [
                'agent_node_id' => (int) $root->id,
                'site_code' => (string) $admin_site->code,
                'is_line_root' => true,
            ],
        ]);
    }
}
