<?php

namespace App\Filament\Resources\Users\Pages;

use App\Filament\Resources\Users\UserResource;
use Filament\Resources\Pages\CreateRecord;
use App\Models\User;
use App\Services\RoleAssignmentService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CreateUser extends CreateRecord
{
    protected static string $resource = UserResource::class;
    protected function handleRecordCreation(array $data): Model
    {
        return DB::transaction(function () use ($data) {
            $roles = $data['roles'] ?? []; unset($data['roles']);
            $user = User::create($data);
            return app(RoleAssignmentService::class)->update(auth()->user(), $user, [], $roles);
        });
    }
}
