<?php

namespace App\Domain\Billing\Models;

use App\Domain\Applicants\Models\Applicant;
use App\Domain\Billing\Enums\InvoiceStatus;
use App\Domain\Identity\Models\User;
use App\Domain\Organization\Models\Branch;
use App\Domain\Organization\Models\Company;
use App\Domain\Payments\Models\Payment;
use App\Domain\Recruitment\Models\JobDemand;
use App\Support\Concerns\HasUuid;
use App\Support\Money\Money;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Invoice extends Model
{
    use HasFactory, HasUuid, SoftDeletes;

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

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

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

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

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

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

    public function lines(): HasMany
    {
        return $this->hasMany(InvoiceLine::class)->orderBy('sort_order');
    }

    public function installments(): HasMany
    {
        // chaperoned: an installment reads its currency from the invoice.
        return $this->hasMany(Installment::class)->orderBy('sequence')->chaperone();
    }

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

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

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

    /** What the applicant still owes. */
    public function outstanding(): Money
    {
        return $this->total()->minus($this->paid());
    }

    public function isFullyPaid(): bool
    {
        return $this->outstanding()->isZero() && ! $this->total()->isZero();
    }

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

    public function scopeOutstanding(Builder $query): Builder
    {
        return $query
            ->whereIn('status', [
                InvoiceStatus::Issued->value,
                InvoiceStatus::PartiallyPaid->value,
                InvoiceStatus::Overdue->value,
            ])
            ->whereColumn('paid_amount', '<', 'total_amount');
    }

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