<?php

namespace App\Domain\Financial\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use App\Domain\Shared\Traits\ScopedThroughBranch;

class InvoiceItem extends Model
{
    use ScopedThroughBranch;

    /**
     * The parent whose branch this row inherits. A line item has no
     * branch of its own and must not grow one — a denormalised copy
     * here is a second source of truth that drifts the first time the
     * parent moves.
     */
    protected static string $branchScopeRelation = 'invoice';

    protected $fillable = [
        'academy_id',
        'invoice_id',
        'itemable_type',
        'itemable_id',
        'description',
        'quantity',
        'unit_price',
        'discount_amount',
        'tax_amount',
        'total_amount',
        'metadata',
        'is_delivered',
        'delivered_at',
        'delivered_by',
    ];

    protected function casts(): array
    {
        return [
            'quantity' => 'integer',
            'unit_price' => 'integer',
            'discount_amount' => 'integer',
            'tax_amount' => 'integer',
            'total_amount' => 'integer',
            'metadata' => 'array',
            'is_delivered' => 'boolean',
            'delivered_at' => 'datetime',
        ];
    }

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

    public function itemable(): MorphTo
    {
        return $this->morphTo();
    }

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