<?php

namespace App\Components\Admin\Role;

use App\Models\User\Permission;
use App\Models\User\Role;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

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

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

        $this->validate();

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

        $historyService->add(
            auth()->user(),
            "Created role '{$role->name}' with " . count($this->permissions) . ' permission(s)',
            [
                'role_id'     => $role->id,
                'permissions' => $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',
        ];
    }
}
