<?php

namespace App\Components\Admin\Permission;

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

class PermissionCreate extends Component {
    use AuthorizesRequests;
    public string $name = '';
    public string $group = '';
    public string $label = '';
    public ?string $description = null;

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

        $this->validate();

        $permission = Permission::create([
            'name' => $this->name,
            'group' => $this->group,
            'label' => $this->label,
            'description' => $this->description,
            'guard_name' => 'web',
        ]);

        $historyService->add(
            auth()->user(),
            "Created permission '{$this->name}' in group '{$this->group}'",
            ['permission_id' => $permission->id]
        );

        return redirect()->route('admin.permissions.index');
    }

    public function render() {
        return view('components.admin.permission.permission-create');
    }

    protected function rules(): array {
        return [
            'name' => 'required|string|unique:permissions,name',
            'group' => 'required|string|max:50',
            'label' => 'required|string|max:100',
            'description' => 'nullable|string|max:255',
        ];
    }
}
