<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class WestWallet extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'currency',
        'ipn_url',
        'address',
        'label',
        'status',
        'balance',
        'last_sync_at',
    ];

    protected $casts = [
        'last_sync_at' => 'datetime',
        'balance' => 'decimal:8',
    ];

    const STATUS_ACTIVE = 'active';
    const STATUS_INACTIVE = 'inactive';
    const STATUS_SUSPENDED = 'suspended';

    /**
     * Get the user that owns the wallet
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get wallet transactions
     */
    public function transactions()
    {
        return $this->hasMany(WestWalletTransaction::class, 'wallet_id');
    }

    /**
     * Get recent transactions
     */
    public function recentTransactions($limit = 10)
    {
        return $this->transactions()
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * Check if wallet is active
     */
    public function isActive()
    {
        return $this->status === self::STATUS_ACTIVE;
    }

    /**
     * Update wallet balance
     */
    public function updateBalance($balance)
    {
        $this->update([
            'balance' => $balance,
            'last_sync_at' => now(),
        ]);
    }

    /**
     * Get formatted balance
     */
    public function getFormattedBalanceAttribute()
    {
        return number_format($this->balance, 8);
    }

    /**
     * Scope for active wallets
     */
    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    /**
     * Scope for specific currency
     */
    public function scopeCurrency($query, $currency)
    {
        return $query->where('currency', $currency);
    }
}
