<?php

namespace App\Actions\User;

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

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

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

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

        $user->load('roles');

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

        return $user;
    }
}
