<?php

namespace App\Domain\Expenses\Models;

use App\Domain\Accounting\Models\LedgerAccount;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use RuntimeException;

/** Money paid out to a vendor (§44). */
class VendorPayment extends Model
{
    use HasUuid;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'amount' => 'integer',
            'paid_on' => 'date',
        ];
    }

    protected static function booted(): void
    {
        // Same rule as applicant collections: money that has moved is history.
        static::updating(fn () => throw new RuntimeException('A vendor payment cannot be edited.'));
        static::deleting(fn () => throw new RuntimeException('Vendor payments cannot be deleted.'));
    }

    public function vendor(): BelongsTo
    {
        return $this->belongsTo(Vendor::class);
    }

    public function bill(): BelongsTo
    {
        return $this->belongsTo(VendorBill::class, 'vendor_bill_id');
    }

    public function paidFromAccount(): BelongsTo
    {
        return $this->belongsTo(LedgerAccount::class, 'paid_from_account_id');
    }

    public function money(): Money
    {
        return Money::of($this->amount, $this->currency);
    }
}
