<?php

namespace App\Livewire\Pages\Settings;

use Illuminate\View\View;
use Livewire\Component;

class ApiTokens extends Component
{
    public string $tokenName = '';

    public ?string $newToken = null;

    public function createToken(): void
    {
        $this->validate(['tokenName' => 'required|string|max:100']);

        $token = auth()->user()->createToken($this->tokenName);
        $this->newToken = $token->plainTextToken;
        $this->tokenName = '';
    }

    public function revokeToken(int $id): void
    {
        auth()->user()->tokens()->where('id', $id)->delete();
    }

    public function dismissNewToken(): void
    {
        $this->newToken = null;
    }

    public function render(): View
    {
        $tokens = auth()->user()->tokens()->latest()->get();

        return view('livewire.pages.settings.api-tokens', compact('tokens'))
            ->layout('layouts.nimuli-app', ['title' => 'API Tokens']);
    }
}
