<?php

// app/Models/DigitalAccount.php

namespace App\Models;

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

class DigitalAccount extends Model
{
    use HasFactory;

    protected $fillable = [
        'merchant_id', 'account_number', 'bank_code', 'balance',
        'status', 'opened_date', 'closed_date', 'metadata',
    ];

    protected $casts = [
        'balance' => 'decimal:2',
        'opened_date' => 'date',
        'closed_date' => 'date',
        'metadata' => 'array',
    ];

    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    public function financialMovements()
    {
        return $this->hasMany(FinancialMovement::class);
    }

    public function credit(float $amount, string $description, array $metadata = [])
    {
        $balanceBefore = $this->balance;
        $this->balance += $amount;
        $this->save();

        return $this->financialMovements()->create([
            'type' => 'credit',
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $this->balance,
            'description' => $description,
            'metadata' => $metadata,
        ]);
    }

    public function debit(float $amount, string $description, array $metadata = [])
    {
        if ($this->balance < $amount) {
            throw new \Exception('Saldo insuficiente');
        }

        $balanceBefore = $this->balance;
        $this->balance -= $amount;
        $this->save();

        return $this->financialMovements()->create([
            'type' => 'debit',
            'amount' => $amount,
            'balance_before' => $balanceBefore,
            'balance_after' => $this->balance,
            'description' => $description,
            'metadata' => $metadata,
        ]);
    }
}
