<?php

namespace App\Models;

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

class WalletLock extends Model
{
    use HasFactory;

    protected $fillable = [
        'wallet_id',
        'user_id',
        'order_id',
        'amount_locked',
        'currency',
        'amount_consumed',
        'status',
        'description',
    ];

    protected $casts = [
        'amount_locked' => 'decimal:8',
        'amount_consumed' => 'decimal:8',
    ];

    // Relationship with wallet
    public function wallet()
    {
        return $this->belongsTo(Wallet::class, 'wallet_id');
    }

    // Relationship with user
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Relationship with order
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    // Scope for active locks
    public function scopeActive($query)
    {
        return $query->whereIn('status', ['active', 'partially_consumed']);
    }

    // Scope for locks by user and currency
    public function scopeForUserAndCurrency($query, $userId, $currency)
    {
        return $query->where('user_id', $userId)->where('currency', $currency);
    }

    // Get remaining locked amount
    public function getRemainingAmountAttribute()
    {
        return $this->amount_locked - $this->amount_consumed;
    }

    // Check if lock is fully consumed
    public function isFullyConsumed()
    {
        return $this->amount_consumed >= $this->amount_locked;
    }

    // Check if lock is available for consumption
    public function isAvailable()
    {
        return $this->status === 'active' || $this->status === 'partially_consumed';
    }
}