<?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\AgentRoleService;
use App\Lottery\ErrorCode;
use App\Support\AdminAgentNodeAccess;
use App\Support\AdminAgentScope;
use App\Support\AdminRoleApiPresenter;
use App\Support\ApiMessage;
use App\Http\Requests\Admin\AgentRoleStoreRequest;

final class AgentNodeRoleStoreController extends Controller
{
    public function __invoke(
        AgentRoleStoreRequest $request,
        AgentNode $agent_node,
        AgentRoleService $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.role.manage')) {
            return ApiMessage::errorResponse(
                $request,
                'admin.agent_role_manage_denied',
                ErrorCode::AdminForbidden->value,
                null,
                403,
            );
        }

        // Agent accounts can only create roles 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_role_manage_denied',
                ErrorCode::AdminForbidden->value,
                null,
                403,
            );
        }

        $role = $service->createForAgent($admin, $agent_node, $request->validated());

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'agent',
            'agent_role.create',
            'admin_role',
            (string) $role->id,
            null,
            AdminRoleApiPresenter::item($role),
        );

        return ApiResponse::success(AdminRoleApiPresenter::item($role));
    }
}
