<?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 DberpOtherStockOutOrderItem extends Model
{
    use HasDberpDocumentLineUnitRelations;

    protected $table = 'dberp_other_stock_out_order_items';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_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',
        'quantity',
        'base_quantity',
        'sort_order',
        'remark',
    ];

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

    protected function casts(): array
    {
        return [
            'order_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',
            'quantity' => 'decimal:4',
            'base_quantity' => 'decimal:4',
            'sort_order' => 'integer',
        ];
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(DberpOtherStockOutOrder::class, 'order_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');
    }
}
