<?php

namespace App\Components\Admin\Users;

use App\Models\API\ApiScope;
use App\Models\User\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class UserApiKeys extends Component {
    use AuthorizesRequests;
    public User $user;

    /** Create token */
    public string $tokenName = '';
    public array $selectedScopes = [];
    public ?string $newToken = null;

    public function mount(User $user): void {
        $this->authorize('viewApiKeys', $user);
        $this->user = $user;
        $this->scopes = ApiScope::orderBy('group')
            ->orderBy('label')
            ->get()
            ->groupBy('group');
    }

    public function createToken(): void {
        $this->authorize('manageApiKeys', $this->user);

        $this->validate([
            'tokenName' => 'required|string|max:100',
            'selectedScopes' => 'array',
        ]);

        $token = $this->user->createToken(
            $this->tokenName,
            $this->selectedScopes
        );

        $this->newToken = $token->plainTextToken;

        $this->reset(['tokenName', 'selectedScopes']);
    }

    public function revokeToken(int $tokenId): void {
        $this->authorize('manageApiKeys', $this->user);

        $this->user->tokens()
            ->where('id', $tokenId)
            ->delete();
    }

    public function render() {
        return view('components.admin.users.user-api-keys', [
            'tokens' => $this->user->tokens()
                ->orderByDesc('created_at')
                ->get(),

            'scopes' => ApiScope::orderBy('group')
                ->orderBy('label')
                ->get()
                ->groupBy('group'),
        ]);
    }
}
