<?php

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

use App\Models\AgentNode;
use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Agent\AgentNodeService;
use App\Support\AdminAgentNodeAccess;
use App\Support\AgentNodePresenter;
use App\Http\Requests\Admin\AgentNodeStoreRequest;

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

        $parent = AgentNode::query()->findOrFail((int) $request->validated('parent_id'));
        $denied = AdminAgentNodeAccess::denyUnlessCanManageParent($admin, $parent);
        if ($denied !== null) {
            return $denied;
        }

        $node = $service->createChild($admin, $request->validated());

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'system',
            'agent_node.create',
            'agent_node',
            (string) $node->id,
            null,
            AgentNodePresenter::item($node),
        );

        return ApiResponse::success(AgentNodePresenter::item($node));
    }
}
