<?php

namespace App\Models\Returns;

use App\Models\Catalog\Product;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\HasDefaultUnitFromProduct;
use App\Models\Inventory\ProductSerial;
use App\Models\Inventory\StockBatch;
use App\Models\Lookups\ReturnReason;
use App\Models\Lookups\UnitOfMeasure;
use App\Models\Sales\Invoice;
use App\Models\Sales\InvoiceItem;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ReturnItem extends Model
{
    use BelongsToTenant, HasDefaultUnitFromProduct;

    protected $fillable = [
        'return_id', 'invoice_id', 'invoice_item_id', 'product_id',
        'unit_id', 'stock_batch_id', 'product_serial_id',
        'return_reason_id', 'quantity', 'unit_price', 'line_total',
        'discount_type', 'discount_value', 'discount_amount',
        'grand_total', 'is_add_back_to_stock', 'reason_note',
    ];

    protected function casts(): array
    {
        return [
            'quantity' => 'decimal:4',
            'unit_price' => 'decimal:2',
            'line_total' => 'decimal:2',
            'discount_value' => 'decimal:2',
            'discount_amount' => 'decimal:2',
            'grand_total' => 'decimal:2',
            'is_add_back_to_stock' => 'boolean',
        ];
    }

    public function returnDoc(): BelongsTo
    {
        return $this->belongsTo(ReturnDoc::class, 'return_id');
    }

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

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

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

    public function unit(): BelongsTo
    {
        return $this->belongsTo(UnitOfMeasure::class, 'unit_id');
    }

    public function reason(): BelongsTo
    {
        return $this->belongsTo(ReturnReason::class, 'return_reason_id');
    }

    public function stockBatch(): BelongsTo
    {
        return $this->belongsTo(StockBatch::class, 'stock_batch_id');
    }

    public function serial(): BelongsTo
    {
        return $this->belongsTo(ProductSerial::class, 'product_serial_id');
    }

    /**
     * Items whose parent return has not been (soft-)deleted.
     *
     * `return_items` has no `deleted_at` of its own — a deleted return leaves its
     * lines in place for the audit trail — so every "already returned" quota/cap
     * calculation must go through this scope instead of querying the table
     * directly, otherwise a deleted return's lines keep counting against the cap.
     */
    public function scopeFromActiveReturn(Builder $query): void
    {
        $query->whereHas('returnDoc');
    }
}
