<?php

namespace App\Components\Admin\Role;

use App\Models\User\Permission;
use Illuminate\Validation\Rule;
use Livewire\Component;
use Spatie\Permission\Models\Role;

class RoleEdit extends Component {
    public Role $role;

    public string $name;
    public array $permissions = [];

    public function mount(Role $role): void {
//        $this->authorize('edit', $role);

        $this->role = $role;
        $this->name = $role->name;
        $this->permissions = $role->permissions->pluck('name')->toArray();
    }

    public function save(): void {
//        $this->authorize('edit', $this->role);
        $this->validate();

        $this->role->update([
            'name' => $this->name,
        ]);

        $this->role->syncPermissions($this->permissions);

        $this->dispatch('toast',
            title: 'Saved',
            message: 'Successfully saved role.',
            type: 'success'
        );
    }

    public function render() {
        return view('components.admin.role.role-edit', [
            'permissionGroups' => Permission::orderBy('group')
                ->orderBy('label')
                ->get()
                ->groupBy('group'),
        ]);
    }

    protected function rules(): array {
        return [
            'name' => [
                'required',
                'string',
                'max:100',
                Rule::unique('roles', 'name')->ignore($this->role->id),
            ],
            'permissions' => ['array'],
        ];
    }
}
