<?php

namespace App\Models;

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

class CryptoFiatSwap extends Model
{
    use HasFactory;

    protected $fillable = [
        'idempotency_key',
        'account_id',
        'crypto_balance_id',
        'crypto_code',
        'network',
        'crypto_amount',
        'rate',
        'fiat_amount',
        'status',
    ];

    protected $casts = [
        'crypto_amount' => 'decimal:8',
        'rate' => 'decimal:8',
        'fiat_amount' => 'decimal:2',
    ];

    /* =====================
    |  Status constants
    ===================== */
    public const STATUS_PENDING = 'pending';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_FAILED = 'failed';

    /* =====================
     |  Relationships
     ===================== */

    /**
     * Fiat account that received the funds
     */
    public function account()
    {
        return $this->belongsTo(Account::class);
    }

    /**
     * Crypto balance that was debited
     */
    public function cryptoBalance()
    {
        return $this->belongsTo(AccountCryptoBalance::class, 'crypto_balance_id');
    }

    /**
     * Ledger transactions for this swap
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class, 'crypto_balance_id', 'crypto_balance_id')
            ->whereIn('type', [
                'swap_debit',
                'swap_credit',
            ]);
    }

    /* =====================
     |  Helpers
     ===================== */

    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    public function isCompleted(): bool
    {
        return $this->status === self::STATUS_COMPLETED;
    }

    public function isFailed(): bool
    {
        return $this->status === self::STATUS_FAILED;
    }
}
