<?php

namespace App\Components\Admin\Permission;

use App\Services\HistoryService;
use Livewire\Component;
use Spatie\Permission\Models\Permission;

class PermissionEdit extends Component {
    public Permission $permission;
    public $selectedRoles = [];

    /**
     * Initialize the component with a specific permission.
     * We pluck the names of the currently assigned roles to populate the checkboxes.
     */
    public function mount(Permission $permission) {
        $this->authorize('edit', $permission);
        $this->permission = $permission;
        $this->selectedRoles = $this->permission->roles()->pluck('name')->toArray();
    }

    /**
     * This method is triggered every time the $selectedRoles array is updated
     * (i.e., when a checkbox is toggled).
     */
    public function updatedSelectedRoles(HistoryService $history) {
        $this->authorize('edit', $this->permission);

        $rolesBefore = $this->permission->roles()->pluck('name')->sort()->values()->toArray();

        // Spatie's syncRoles handles adding/removing relationships automatically.
        $this->permission->syncRoles($this->selectedRoles);

        $rolesAfter = collect($this->selectedRoles)->sort()->values()->toArray();

        if ($rolesBefore !== $rolesAfter) {
            $history->addForActor("Permission '{$this->permission->name}' role assignments changed", [
                'permission_id' => $this->permission->id,
                'name'          => $this->permission->name,
                'added'         => array_values(array_diff($rolesAfter, $rolesBefore)),
                'removed'       => array_values(array_diff($rolesBefore, $rolesAfter)),
            ]);
        }

        $this->dispatch('toast', message: 'Roles updated', type: 'success');
    }

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