<?php

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

use App\Filament\Tenant\Resources\UserResource;
use Filament\Actions;
use Filament\Resources\Pages\EditRecord;

class EditUser extends EditRecord
{
    protected static string $resource = UserResource::class;

    protected function getHeaderActions(): array
    {
        return [Actions\DeleteAction::make()];
    }

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

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

    protected function afterSave(): void
    {
        // Always include the primary role
        $picked = $this->_rolesPicked;
        if (! in_array($this->record->role, $picked, true)) {
            $picked[] = $this->record->role;
        }
        $this->record->syncRoles(array_unique($picked));
    }
}
