<?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\AdminAgentScope;
use App\Support\AgentNodePresenter;
use App\Http\Requests\Admin\AgentNodeUpdateRequest;

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

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

        if (! AdminAgentScope::nodeManageableBy($admin, $agent_node)) {
            return AdminAgentNodeAccess::denyUnlessNodeVisible($admin, $agent_node)
                ?? AdminAgentNodeAccess::denyUnlessCanManageParent($admin, $agent_node);
        }

        if ($agent_node->isRoot() && ! $admin->isSuperAdmin()) {
            return AdminAgentNodeAccess::denyUnlessCanManageParent($admin, $agent_node);
        }

        $before = AgentNodePresenter::item($agent_node);
        $node = $service->update($agent_node, $request->validated());
        $after = AgentNodePresenter::item($node);

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'system',
            'agent_node.update',
            'agent_node',
            (string) $node->id,
            $before,
            $after,
        );

        return ApiResponse::success($after);
    }
}
