<?php

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

use App\Auth\Permissions;
use App\Filament\Tenant\Resources\RoleResource;
use Filament\Resources\Pages\EditRecord;
use Spatie\Permission\PermissionRegistrar;

class EditRole extends EditRecord
{
    protected static string $resource = RoleResource::class;

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Collect all picked permissions across the module check-lists.
        $picked = [];
        foreach (Permissions::grouped() as $module => $_) {
            $key = "permissions_{$module}";
            if (isset($data[$key]) && is_array($data[$key])) {
                $picked = array_merge($picked, $data[$key]);
            }
            unset($data[$key]);
        }
        $this->_pickedPermissions = $picked;
        return $data;
    }

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

    protected function afterSave(): void
    {
        $this->record->syncPermissions($this->_pickedPermissions);
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
}
