<?php

namespace App\Components\Admin\Permission;

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

class PermissionEdit extends Component {
    use AuthorizesRequests;
    public Permission $permission;
    public $selectedRoles = [];
    public array $previousRoles = [];

    /**
     * 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->previousRoles = $this->selectedRoles;
    }

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

        $added   = array_values(array_diff($this->selectedRoles, $this->previousRoles));
        $removed = array_values(array_diff($this->previousRoles, $this->selectedRoles));

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

        if ($added || $removed) {
            $parts = [];
            if ($added)   $parts[] = 'added: ' . implode(', ', $added);
            if ($removed) $parts[] = 'removed: ' . implode(', ', $removed);

            $historyService->add(
                auth()->user(),
                "Updated role assignments for permission '{$this->permission->name}' — " . implode('; ', $parts),
                [
                    'permission_id' => $this->permission->id,
                    'added'         => $added,
                    'removed'       => $removed,
                ]
            );
        }

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

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