<?php

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

use App\Models\AdminUser;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminAccountScopeGuard;
use App\Support\AdminUserApiPresenter;
use App\Support\AdminPlatformUserSiteGuard;
use App\Http\Requests\Admin\AdminUserRoleSyncRequest;

/** PUT /api/v1/admin/admin-users/{admin_user}/roles */
final class AdminUserRoleSyncController extends Controller
{
    public function __invoke(AdminUserRoleSyncRequest $request, AdminUser $admin_user): JsonResponse
    {
        /** @var AdminUser $actor */
        $actor = $request->lotteryAdmin();

        AdminAccountScopeGuard::assertPlatformAccount($admin_user);

        $siteId = (int) $request->validated('admin_site_id');
        AdminPlatformUserSiteGuard::assertActorCanAssignSite($actor, $siteId);

        $slugs = array_values(array_unique($request->validated('role_slugs')));
        $admin_user->syncSystemRoleSlugsForSite($siteId, $slugs);

        $admin_user->load('roles');

        return ApiResponse::success(AdminUserApiPresenter::listItem($admin_user));
    }
}
