<?php

namespace App\Domain\Billing\Models;

use App\Domain\Billing\Enums\InstallmentStatus;
use App\Domain\Workflow\Models\PipelineStage;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Installment extends Model
{
    use HasFactory, HasUuid;

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

    protected function casts(): array
    {
        return [
            'status' => InstallmentStatus::class,
            'due_on' => 'date',
        ];
    }

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

    public function blockingStage(): BelongsTo
    {
        return $this->belongsTo(PipelineStage::class, 'blocking_stage_id');
    }

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

    public function outstanding(): Money
    {
        $currency = $this->invoice->currency;

        return Money::of((int) $this->amount, $currency)
            ->minus(Money::of((int) $this->paid_amount, $currency));
    }

    public function isOverdue(): bool
    {
        return ! $this->status->isSettled()
            && $this->due_on !== null
            && $this->due_on->isPast();
    }
}
