<?php

namespace App\Components\Admin\Role;

use App\Models\User\Permission;
use App\Models\User\Role;
use Livewire\Component;

class RoleCreate extends Component {
    public string $name = '';
    public array $permissions = [];

    public function save() {
        $this->authorize('create', Role::class);

        $this->validate();

        $role = Role::create(['name' => $this->name]);
        $role->syncPermissions($this->permissions);

        return redirect()->route('admin.roles.show', $role);
    }

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

    protected function rules(): array {
        return [
            'name' => 'required|string|max:100|unique:roles,name',
            'permissions' => 'array',
        ];
    }
}
