<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Observers\UserObserver;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;

#[Fillable(['name', 'email', 'cedula', 'password', 'phone', 'role_id', 'vip_level_id', 'points_balance', 'wallet_balance', 'phone_verified_at', 'referred_by_id', 'referral_code', 'status', 'fcm_token'])]
#[Hidden(['password', 'remember_token'])]
#[ObservedBy(UserObserver::class)]
class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'phone_verified_at' => 'datetime',
            'password' => 'hashed',
            'points_balance' => 'integer',
            'wallet_balance' => 'decimal:2',
            'referred_by_id' => 'integer',
            'role_id' => 'integer',
            'vip_level_id' => 'integer',
        ];
    }

    public function resellerProfile()
    {
        return $this->hasOne(ResellerProfile::class);
    }

    public function resellerRequests()
    {
        return $this->hasMany(ResellerRequest::class);
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function keys()
    {
        return $this->hasMany(UserKey::class);
    }

    public function actionTickets()
    {
        return $this->hasMany(ActionTicket::class);
    }

    public function chestOpenings()
    {
        return $this->hasMany(ChestOpening::class);
    }

    public function pointsLogs()
    {
        return $this->hasMany(PointsLog::class);
    }

    public function referredBy()
    {
        return $this->belongsTo(User::class, 'referred_by_id');
    }

    public function referrals()
    {
        return $this->hasMany(User::class, 'referred_by_id');
    }

    /**
     * Genera un código de referido único a partir del primer nombre.
     */
    public static function generateUniqueReferralCode(string $name): string
    {
        $base = Str::upper(Str::slug(explode(' ', trim($name))[0] ?: 'USER', ''));
        $base = $base !== '' ? $base : 'USER';

        do {
            $code = $base . '-' . Str::upper(Str::random(2));
        } while (self::where('referral_code', $code)->exists());

        return $code;
    }

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function vipLevel()
    {
        return $this->belongsTo(VipLevel::class, 'vip_level_id');
    }
}
