<?php

namespace App\Livewire\Traits;

use App\Models\EinundzwanzigPleb;
use App\Support\NostrAuth;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\On;

trait WithNostrAuth
{
    public ?string $currentPubkey = null;

    public ?object $currentPleb = null;

    public bool $isAllowed = false;

    public bool $canEdit = false;

    #[On('nostrLoggedIn')]
    public function handleNostrLogin($signedEvent = null): void
    {
        $executed = RateLimiter::attempt(
            'nostr-login:'.request()->ip(),
            10,
            function () {},
        );

        if (! $executed) {
            abort(429, 'Too many login attempts.');
        }

        $pubkey = NostrAuth::loginWithSignedEvent($signedEvent);

        $this->currentPubkey = $pubkey;
        $this->currentPleb = EinundzwanzigPleb::query()
            ->where('pubkey', $pubkey)
            ->first();

        if ($this->currentPleb && $this->currentPleb->isBoardMember()) {
            $this->canEdit = true;
        }

        $this->isAllowed = true;
    }

    #[On('nostrLoggedOut')]
    public function handleNostrLogout(): void
    {
        NostrAuth::logout();

        $this->isAllowed = false;
        $this->currentPubkey = null;
        $this->currentPleb = null;
        $this->canEdit = false;
    }

    public function mountWithNostrAuth(): void
    {
        if ($user = NostrAuth::user()) {
            $this->currentPubkey = $user->getPubkey();
            $this->currentPleb = $user->getPleb();
            $this->isAllowed = true;

            if ($this->currentPleb && $this->currentPleb->isBoardMember()) {
                $this->canEdit = true;
            }
        }
    }
}
