<?php

namespace App\Livewire;

use App\Models\AuthenticationToken;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('components.layouts.app')]
class ManageAuthenticationTokens extends Component
{
    #[Computed]
    public function tokens()
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();

        return $user->tokens()
            ->with('application')
            ->orderBy('issued_at', 'desc')
            ->get()
            ->groupBy('application.name')
            ->sortKeys();
    }

    public function revokeToken($tokenId)
    {
        $token = AuthenticationToken::where('id', $tokenId)
            ->where('user_id', Auth::id())
            ->first();

        if ($token) {
            $token->delete();
            $this->dispatch('token-revoked');
        }
    }

    public function render()
    {
        return view('livewire.manage-authentication-tokens')->title('Authentication Tokens');
    }
}
