<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Invoices\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Maestro\Core\Modules\Customers\Models\Customer;
use Maestro\Core\Modules\Invoices\Enums\InvoiceStatus;
use Maestro\Core\Modules\Invoices\Enums\InvoiceType;
use Maestro\Core\Modules\Invoices\Enums\IssuedVia;

class Invoice extends Model
{
    /**
     * @var list<string>
     */
    protected $fillable = [
        'type',
        'status',
        'issued_via',
        'document_number',
        'fiscal_year',
        'sequence_value',
        'customer_id',
        'credited_invoice_id',
        'invoice_date',
        'expiration_date',
        'description',
        'email_body',
        'subtotal_ex_vat',
        'total_vat',
        'total_inc_vat',
        'finalized_at',
        'email_sent_at',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'type' => InvoiceType::class,
            'status' => InvoiceStatus::class,
            'issued_via' => IssuedVia::class,
            'invoice_date' => 'date',
            'expiration_date' => 'date',
            'subtotal_ex_vat' => 'decimal:2',
            'total_vat' => 'decimal:2',
            'total_inc_vat' => 'decimal:2',
            'finalized_at' => 'datetime',
            'email_sent_at' => 'datetime',
        ];
    }

    /**
     * @return BelongsTo<Customer, Invoice>
     */
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    /**
     * @return BelongsTo<Invoice, Invoice>
     */
    public function creditedInvoice(): BelongsTo
    {
        return $this->belongsTo(self::class, 'credited_invoice_id');
    }

    /**
     * @return HasMany<InvoiceLine, Invoice>
     */
    public function lines(): HasMany
    {
        return $this->hasMany(InvoiceLine::class)->orderBy('sort_order')->orderBy('id');
    }

    public function isDraft(): bool
    {
        return $this->status === InvoiceStatus::Draft;
    }

    public function isFinalized(): bool
    {
        return $this->status === InvoiceStatus::Finalized;
    }
}
