<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\Product\DberpDocumentLineUnitService;
use App\Models\Concerns\HasDberpDocumentLineUnitRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpPurchaseReturnOrderItem extends Model
{
    use HasDberpDocumentLineUnitRelations;

    protected $table = 'dberp_purchase_return_order_items';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_id',
        'purchase_order_item_id',
        'purchase_receipt_item_id',
        'product_id',
        'product_sku_id',
        'product_sku_code',
        'product_sku_name',
        'product_sku_spec',
        'unit_id',
        'unit_name',
        'base_unit_id',
        'auxiliary_unit_id',
        'is_auxiliary_unit',
        'auxiliary_unit_quantity',
        'base_unit_quantity',
        'source_batch_id',
        'batch_no',
        'production_date',
        'expiry_date',
        'shelf_life_days',
        'batch_allocations',
        'serial_numbers',
        'return_quantity',
        'base_return_quantity',
        'unit_price',
        'return_amount',
        'sort_order',
        'remark',
    ];

    protected static function booted(): void
    {
        static::saving(function (self $item): void {
            DberpDocumentLineUnitService::applySnapshotsToLine($item);

            $returnQuantity = (float) ($item->return_quantity ?? 0);
            $unitPrice = (float) ($item->unit_price ?? 0);

            $item->setAttribute('return_amount', number_format($returnQuantity * $unitPrice, 4, '.', ''));
        });

        static::saved(function (self $item): void {
            $item->order?->forceFill([
                'total_return_quantity' => (string) $item->order->items()->sum('return_quantity'),
                'total_amount' => (string) $item->order->items()->sum('return_amount'),
            ])->save();
        });

        static::deleted(function (self $item): void {
            $item->order?->forceFill([
                'total_return_quantity' => (string) $item->order->items()->sum('return_quantity'),
                'total_amount' => (string) $item->order->items()->sum('return_amount'),
            ])->save();
        });
    }

    protected function casts(): array
    {
        return [
            'order_id' => 'integer',
            'purchase_order_item_id' => 'integer',
            'purchase_receipt_item_id' => 'integer',
            'product_id' => 'integer',
            'product_sku_id' => 'integer',
            'unit_id' => 'integer',
            'base_unit_id' => 'integer',
            'auxiliary_unit_id' => 'integer',
            'is_auxiliary_unit' => 'boolean',
            'auxiliary_unit_quantity' => 'decimal:6',
            'base_unit_quantity' => 'decimal:6',
            'source_batch_id' => 'integer',
            'production_date' => 'date',
            'expiry_date' => 'date',
            'shelf_life_days' => 'integer',
            'batch_allocations' => 'array',
            'serial_numbers' => 'array',
            'return_quantity' => 'decimal:4',
            'base_return_quantity' => 'decimal:4',
            'unit_price' => 'decimal:4',
            'return_amount' => 'decimal:4',
            'sort_order' => 'integer',
        ];
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseReturnOrder::class, 'order_id');
    }

    public function purchaseOrderItem(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseOrderItem::class, 'purchase_order_item_id');
    }

    public function purchaseReceiptItem(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseReceiptOrderItem::class, 'purchase_receipt_item_id');
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(DberpProduct::class, 'product_id');
    }

    public function productSku(): BelongsTo
    {
        return $this->belongsTo(DberpProductSku::class, 'product_sku_id');
    }

    public function sourceBatch(): BelongsTo
    {
        return $this->belongsTo(DberpInventoryBatch::class, 'source_batch_id');
    }
}
