<?php

namespace App\Actions\User;

use App\DTOs\UserData;
use App\Events\ModelChanged;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;

class UpdateUserAction
{
    public function __construct(private UserRepositoryInterface $repository) {}

    public function execute(User $user, UserData $data): User
    {
        /** @var User */
        $user = $this->repository->update($user, $data->toArray());

        if ($data->role !== null) {
            $user->syncRoles([$data->role]);
        }

        $user->load('roles');

        ModelChanged::dispatch(User::class, 'updated');

        return $user;
    }
}
