<?php

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

use App\Models\AdminUser;
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\AdminUserApiPresenter;
use App\Support\ApiMessage;
use App\Http\Requests\Admin\AgentAdminUserRoleSyncRequest;

final class AgentAdminUserRoleSyncController extends Controller
{
    public function __invoke(
        AgentAdminUserRoleSyncRequest $request,
        AdminUser $admin_user,
        AgentAdminUserService $service,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $agent = $admin_user->primaryAgentNode();
        if ($agent === null) {
            abort(404);
        }

        $denied = AdminAgentNodeAccess::denyUnlessNodeVisible($admin, $agent);
        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,
            );
        }

        $before = AdminUserApiPresenter::listItem($admin_user);
        $user = $service->syncRoles($agent, $admin_user, $request->validated('role_ids'));
        $after = AdminUserApiPresenter::listItem($user);

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'agent',
            'agent_admin_user.sync_roles',
            'admin_user',
            (string) $user->id,
            $before,
            $after,
        );

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