<?php

namespace App\Domain\Expenses\Models;

use App\Domain\Accounting\Models\LedgerAccount;
use App\Domain\Applicants\Models\Applicant;
use App\Domain\Expenses\Enums\ExpenseStatus;
use App\Domain\Identity\Models\User;
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\BelongsTo;
use RuntimeException;

/**
 * One item of agency spending (§39).
 *
 * Once paid the record is closed to editing: the money has left and the books
 * have been posted, so a correction is a reversal rather than a rewrite.
 */
class Expense extends Model
{
    use HasUuid;

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

    protected function casts(): array
    {
        return [
            'status' => ExpenseStatus::class,
            'amount' => 'integer',
            'tax_amount' => 'integer',
            'total_amount' => 'integer',
            'expense_date' => 'date',
            'paid_on' => 'date',
            'requested_at' => 'datetime',
            'approved_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::updating(function (self $expense) {
            if ($expense->getOriginal('status') !== ExpenseStatus::Paid) {
                return;
            }

            throw new RuntimeException('A paid expense cannot be edited; reverse its journal instead.');
        });

        static::deleting(fn () => throw new RuntimeException('Expenses cannot be deleted.'));
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(ExpenseCategory::class, 'expense_category_id');
    }

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

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

    public function requestedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'requested_by');
    }

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

    public function total(): Money
    {
        return Money::of((int) $this->total_amount, $this->currency);
    }

    public function scopeAwaitingApproval(Builder $query): Builder
    {
        return $query->where('status', ExpenseStatus::Requested->value);
    }

    public function scopeAwaitingPayment(Builder $query): Builder
    {
        return $query->where('status', ExpenseStatus::Approved->value);
    }
}
