<?php

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

use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Models\AgentNode;
use App\Support\AdminIntegrationSiteAccess;
use App\Support\AdminIntegrationSitePresenter;

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

        $sites = AdminIntegrationSiteAccess::queryFor($admin)->get();
        $rootSiteIds = AgentNode::query()
            ->where('depth', 0)
            ->whereIn('admin_site_id', $sites->pluck('id'))
            ->pluck('admin_site_id')
            ->flip();

        $items = $sites
            ->map(static fn ($site): array => AdminIntegrationSitePresenter::listItem(
                $site,
                isset($rootSiteIds[(int) $site->id]),
            ))
            ->all();

        return ApiResponse::success(['items' => $items]);
    }
}
