<?php

namespace App\Models;

use App\Enums\UserKycStatus;
use Database\Factories\UserFactory;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Fortify\TwoFactorAuthenticatable;

#[Fillable(['first_name', 'last_name', 'email', 'contact_number', 'country', 'password', 'is_admin', 'kyc_status', 'kyc_rejection_reason', 'referral_code', 'referred_by_user_id', 'referral_program_enabled', 'jabes_women_enabled', 'blocked_at'])]
#[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable, TwoFactorAuthenticatable;

    /**
     * The accessors to append to the model's array form.
     *
     * @var array<int, string>
     */
    protected $appends = ['name'];

    protected static function booted(): void
    {
        static::creating(function (User $user): void {
            if (blank($user->referral_code)) {
                $user->referral_code = self::generateReferralCode();
            }
        });
    }

    public static function generateReferralCode(): string
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (self::query()->where('referral_code', $code)->exists());

        return $code;
    }

    /**
     * True when assigning {@see $potentialReferrerUserId} as referrer for {@see $assigneeUserId}
     * would create a cycle in the referred_by chain.
     */
    public static function manualReferralWouldCreateCycle(int $assigneeUserId, int $potentialReferrerUserId): bool
    {
        if ($assigneeUserId === $potentialReferrerUserId) {
            return true;
        }

        $cursorId = $potentialReferrerUserId;

        for ($i = 0; $i < 1000 && $cursorId !== null; $i++) {
            if ($cursorId === $assigneeUserId) {
                return true;
            }

            $cursorId = self::query()->whereKey($cursorId)->value('referred_by_user_id');
        }

        return false;
    }

    /**
     * Get the user's full name.
     *
     * @return Attribute<string, never>
     */
    protected function name(): Attribute
    {
        return Attribute::get(fn (): string => trim($this->first_name.' '.$this->last_name));
    }

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'two_factor_confirmed_at' => 'datetime',
            'is_admin' => 'boolean',
            'kyc_status' => UserKycStatus::class,
            'referral_program_enabled' => 'boolean',
            'jabes_women_enabled' => 'boolean',
            'blocked_at' => 'datetime',
        ];
    }

    public function investorPortalUnlocked(): bool
    {
        if ($this->is_admin) {
            return true;
        }

        return $this->kyc_status === UserKycStatus::Approved;
    }

    /**
     * @return HasOne<UserKycProfile, User>
     */
    public function kycProfile(): HasOne
    {
        return $this->hasOne(UserKycProfile::class);
    }

    /**
     * @return HasMany<UserWallet, User>
     */
    public function wallets(): HasMany
    {
        return $this->hasMany(UserWallet::class)->orderByDesc('is_default')->orderBy('id');
    }

    /**
     * @return HasMany<Investment, User>
     */
    public function investments(): HasMany
    {
        return $this->hasMany(Investment::class);
    }

    /**
     * @return BelongsTo<User, User>
     */
    public function referrer(): BelongsTo
    {
        return $this->belongsTo(self::class, 'referred_by_user_id');
    }

    /**
     * @return HasMany<User, User>
     */
    public function directReferrals(): HasMany
    {
        return $this->hasMany(self::class, 'referred_by_user_id');
    }

    /**
     * @return HasMany<InvestmentTransaction, User>
     */
    public function referralTransactions(): HasMany
    {
        return $this->hasMany(InvestmentTransaction::class, 'beneficiary_user_id');
    }
}
