<?php

namespace App\Livewire\Modals;

use Illuminate\View\View;
use Laravel\Sanctum\PersonalAccessToken;
use LivewireUI\Modal\ModalComponent;

class RevokeApiToken extends ModalComponent
{
    public int $tokenId = 0;

    public string $tokenName = '';

    public function mount(int $tokenId): void
    {
        $token = PersonalAccessToken::where('id', $tokenId)
            ->where('tokenable_id', auth()->id())
            ->where('tokenable_type', get_class(auth()->user()))
            ->firstOrFail();

        $this->tokenId = $tokenId;
        $this->tokenName = $token->name;
    }

    public function revoke(): void
    {
        PersonalAccessToken::where('id', $this->tokenId)
            ->where('tokenable_id', auth()->id())
            ->where('tokenable_type', get_class(auth()->user()))
            ->firstOrFail()
            ->delete();

        $this->dispatch('apiTokenRevoked', tokenId: $this->tokenId);
        $this->closeModal();
    }

    public static function modalMaxWidth(): string
    {
        return 'sm';
    }

    public function render(): View
    {
        return view('livewire.modals.revoke-api-token');
    }
}
