<?php

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

use App\Models\AdminRole;
use App\Support\ApiResponse;
use App\Services\AuditLogger;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Agent\AgentRoleService;
use App\Support\AgentRoleAuthorization;
use App\Support\AdminRoleApiPresenter;

final class AgentRoleDestroyController extends Controller
{
    public function __invoke(
        \Illuminate\Http\Request $request,
        AdminRole $admin_role,
        AgentRoleService $service,
    ): JsonResponse {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        if (! $admin_role->isAgentScoped()) {
            abort(404);
        }

        $denied = AgentRoleAuthorization::denyUnlessRoleManageable($admin, $admin_role);
        if ($denied !== null) {
            return $denied;
        }

        $before = AdminRoleApiPresenter::item($admin_role);
        $service->destroy($admin_role);

        AuditLogger::recordForAdmin(
            $admin,
            $request,
            'agent',
            'agent_role.destroy',
            'admin_role',
            (string) $admin_role->id,
            $before,
            null,
        );

        return ApiResponse::success(null);
    }
}
