<?php

namespace App\Http\Controllers\Api\Users;

use App\Http\Controllers\Controller;
use App\Http\Requests\Users\UpdateUserRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class UserUpdateController extends Controller
{
    public function __invoke(UpdateUserRequest $request, string $user): JsonResponse
    {
        $record = User::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->findOrFail($user);

        $record->update($request->safe()->except(['role']));

        if ($request->filled('role')) {
            app(PermissionRegistrar::class)->setPermissionsTeamId($request->user()->tenant_id);
            $role = Role::findByName($request->validated('role'), 'web');
            $record->syncRoles([$role]);
            app(PermissionRegistrar::class)->setPermissionsTeamId(null);
        }

        return response()->json([
            'data' => [
                'id' => $record->id,
                'fullName' => $record->full_name,
                'status' => $record->status,
                'roles' => $record->roles->pluck('name')->values()->all(),
            ],
        ]);
    }
}
