<?php

namespace App\Livewire\Admin\User;

use Livewire\Component;
use Livewire\Attributes\On;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Support\Facades\Auth;
use Exception;

class DeleteUser extends Component
{

    #[On('confirm-delete-user')]
    public function deleteUser(UserService $userService, $payload)
    {
        try {

            $this->authorize('deleteUser', Auth::user());

            $deletedUser = User::findOrFail($payload);
            if ($deletedUser) {
                $deletedUser =  $userService->deleteUser($deletedUser);
            }

            $this->dispatch('user-deleted');
            $this->dispatch('notify', message: $deletedUser->name . ' Usuário excluído com sucesso!');
        } catch (Exception $e) {
            $this->dispatch('user-delete-error');
            $this->dispatch('notify', message: $e->getMessage(), type: 'error');
        }
    }

    public function render()
    {
        return '<div></div>';
    }
}
