<?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\AdminPermissionInheritance;
use App\Support\AgentRoleAuthorization;
use App\Support\AdminRoleApiPresenter;
use App\Http\Requests\Admin\AgentRolePermissionSyncRequest;

final class AgentRolePermissionSyncController extends Controller
{
    public function __invoke(
        AgentRolePermissionSyncRequest $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;
        }

        if ($admin_role->isReadOnlyTemplate()) {
            return AgentRoleAuthorization::denyUnlessRoleManageable($admin, $admin_role);
        }

        $slugs = AdminPermissionInheritance::expand(
            array_values(array_unique($request->validated('permission_slugs'))),
        );
        $before = AdminRoleApiPresenter::item($admin_role);
        $role = $service->syncPermissions($admin, $admin_role, $slugs);

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

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