<?php

namespace App\Components\Admin\Role;

use App\Models\User\Permission;
use App\Services\HistoryService;
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(HistoryService $history): void {
//        $this->authorize('edit', $this->role);
        $this->validate();

        $nameBefore = $this->role->name;
        $permsBefore = $this->role->permissions->pluck('name')->sort()->values()->toArray();

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

        $this->role->syncPermissions($this->permissions);
        $permsAfter = $this->role->fresh()->permissions->pluck('name')->sort()->values()->toArray();

        $context = ['role_id' => $this->role->id, 'name' => $this->name];
        if ($nameBefore !== $this->name) {
            $context['name_change'] = ['from' => $nameBefore, 'to' => $this->name];
        }
        if ($permsBefore !== $permsAfter) {
            $context['permissions'] = [
                'added'   => array_values(array_diff($permsAfter, $permsBefore)),
                'removed' => array_values(array_diff($permsBefore, $permsAfter)),
            ];
        }

        $history->addForActor("Role '{$this->name}' updated", $context);

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