<?php

namespace App\Domain\Expenses\Models;

use App\Domain\Expenses\Enums\VendorType;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/** A supplier the agency owes money to (§43). */
class Vendor extends Model
{
    use HasUuid, SoftDeletes;

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

    protected $hidden = ['bank_account_number'];

    protected function casts(): array
    {
        return [
            'vendor_type' => VendorType::class,
            'payment_terms_days' => 'integer',
        ];
    }

    public function bills(): HasMany
    {
        return $this->hasMany(VendorBill::class);
    }

    public function payments(): HasMany
    {
        return $this->hasMany(VendorPayment::class);
    }

    /** What is still owed across every approved, unpaid bill. */
    public function outstanding(): Money
    {
        $total = (int) $this->bills()
            ->outstanding()
            ->selectRaw('COALESCE(SUM(total_amount - paid_amount), 0) as due')
            ->value('due');

        return Money::of(max(0, $total), $this->currency);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', 'active');
    }
}
