<?php

namespace App\Filament\Resources\Roles\Pages;

use App\Filament\Resources\Roles\RoleResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Permission;

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

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

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        $permissions = collect([
            $data['users_permissions'] ?? []
        ])->flatten()->toArray();

        $record->update([
            'name' => $data['name']
        ]);

        // Assign permissions after the role is saved
        $permissions = Permission::query()->whereIn('name', $permissions)->get();
        $record->syncPermissions($permissions);

        return $record;
    }
}
