<?php

namespace App\Filament\Tenant\Resources\UserResource\Pages;

use App\Filament\Tenant\Resources\UserResource;
use Filament\Resources\Pages\CreateRecord;

class CreateUser extends CreateRecord
{
    protected static string $resource = UserResource::class;

    /** @var array<string> */
    protected array $_rolesPicked = [];

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $this->_rolesPicked = $data['roles_picked'] ?? [];
        unset($data['roles_picked']);
        return $data;
    }

    protected function afterCreate(): void
    {
        $picked = $this->_rolesPicked;
        if (! in_array($this->record->role, $picked, true)) {
            $picked[] = $this->record->role;
        }
        $this->record->syncRoles(array_unique($picked));
    }
}
