<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasOne;
use App\Observers\AccountObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[ObservedBy([AccountObserver::class])]
class Account extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function getTypeAttribute(): string
    {
        return $this->accountType->type;
    }

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

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

    public function getStartingBalanceAttribute()
    {
        if ($this->balances()->exists()) {
            return $this->balances()
                ->where('is_starting', true)
                ->orderBy('id', 'desc')->first()->balance;
        }

        return null;
    }

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

    public function latestBalance(): HasOne
    {
        return $this->hasOne(Balance::class)->latestOfMany();
    }

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

    public function getCurrentBalanceAttribute()
    {
        if ($this->balances()->exists()) {
            return $this->balances()
                ->orderBy('id', 'desc')->first()->balance;
        }

        return null;
    }
}
