<?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\AgentAdminUserService;
use App\Lottery\ErrorCode;
use App\Support\AdminAgentNodeAccess;
use App\Support\AdminAgentScope;
use App\Support\AdminUserApiPresenter;
use App\Support\ApiMessage;
use App\Http\Requests\Admin\AgentAdminUserStoreRequest;

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

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

        if (! $admin->isSuperAdmin() && ! $admin->hasPermissionCode('agent.user.manage')) {
            return ApiMessage::errorResponse(
                $request,
                'admin.agent_user_manage_denied',
                ErrorCode::AdminForbidden->value,
                null,
                403,
            );
        }

        if (! AdminAgentScope::nodeManageableBy($admin, $agent_node)) {
            return AdminAgentNodeAccess::denyUnlessCanManageParent($admin, $agent_node)
                ?? ApiMessage::errorResponse(
                    $request,
                    'admin.agent_user_manage_denied',
                    ErrorCode::AdminForbidden->value,
                    null,
                    403,
                );
        }

        // Agent accounts can only create admin users on their own node, not descendants
        $primaryNode = AdminAgentScope::primaryAgentNode($admin);
        if ($primaryNode !== null && (int) $primaryNode->id !== (int) $agent_node->id) {
            return ApiMessage::errorResponse(
                $request,
                'admin.agent_user_manage_denied',
                ErrorCode::AdminForbidden->value,
                null,
                403,
            );
        }

        $user = $service->createUnderAgent($agent_node, $request->validated());

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'agent',
            'agent_admin_user.create',
            'admin_user',
            (string) $user->id,
            null,
            AdminUserApiPresenter::listItem($user),
        );

        return ApiResponse::success(AdminUserApiPresenter::listItem($user))->setStatusCode(201);
    }
}
