<?php

namespace App\Models;

use App\Enums\AssociationStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use ParagonIE\CipherSweet\BlindIndex;
use ParagonIE\CipherSweet\EncryptedRow;
use Spatie\LaravelCipherSweet\Concerns\UsesCipherSweet;
use Spatie\LaravelCipherSweet\Contracts\CipherSweetEncrypted;

class EinundzwanzigPleb extends Authenticatable implements CipherSweetEncrypted
{
    use HasFactory;
    use UsesCipherSweet;

    /** @var list<string> */
    protected $fillable = [
        'npub',
        'pubkey',
        'email',
        'no_email',
        'nip05_handle',
        'association_status',
        'application_text',
        'archived_application_text',
    ];

    protected function casts(): array
    {
        return [
            'association_status' => AssociationStatus::class,
        ];
    }

    public static function configureCipherSweet(EncryptedRow $encryptedRow): void
    {
        $encryptedRow
            ->addOptionalTextField('email')
            ->addBlindIndex('email', new BlindIndex('email_index'));
    }

    public function profile()
    {
        return $this->hasOne(Profile::class, 'pubkey', 'pubkey');
    }

    public function paymentEvents()
    {
        return $this->hasMany(PaymentEvent::class);
    }

    public function isBoardMember(): bool
    {
        return in_array($this->npub, config('einundzwanzig.config.current_board', []), true);
    }

    public function hasPaidMembership(?int $year = null): bool
    {
        return $this->association_status->value > 1
            && $this->paymentEvents()
                ->where('year', $year ?? (int) date('Y'))
                ->where('paid', true)
                ->exists();
    }
}
