<?php

namespace App\Models;

use App\Traits\VisibleToAdmin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Transfer extends Model
{
    use HasFactory;
    use VisibleToAdmin;

    // This tells the trait how to reach the user who controls visibility
    protected function adminVisibilityRelation(): string
    {
        return 'account.profile.user';
    }

    public const TYPE_LOCAL = 'local';
    public const TYPE_INTERNATIONAL = 'international';

    public const STATUS_PENDING = 'pending';
    public const STATUS_COMPLETED = 'completed';
    public const STATUS_FAILED = 'failed';

    protected $fillable = [
        'account_id',
        'payment_method_id',
        'idempotency_key',
        'type',
        'amount',
        'fee',
        'total',
        'meta',
        'status',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'fee' => 'decimal:2',
        'total' => 'decimal:2',
        'meta' => 'array',
    ];

    public function sourceAccount()
    {
        return $this->belongsTo(Account::class, 'account_id');
    }

    public function paymentMethod()
    {
        return $this->belongsTo(PaymentMethod::class);
    }

    public function account()
    {
        return $this->sourceAccount();
    }

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

    public function totalWithFee(): string
    {
        return bcadd(
            (string) $this->amount,
            (string) $this->fee,
            2
        );
    }

    public function getMetaField(string $key, $default = null)
    {
        return data_get($this->meta ?? [], $key, $default);
    }
}
