<?php

namespace App\Components\Admin\Role;

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

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

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

        $this->validate();

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

        $history->addForActor("Role '{$this->name}' created", [
            'role_id'     => $role->id,
            'name'        => $this->name,
            'permissions' => $role->permissions->pluck('name')->values()->toArray(),
        ]);

        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',
        ];
    }
}
