<?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;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DberpPurchaseInquiryItem extends Model
{
    use HasDberpDocumentLineUnitRelations;

    protected $table = 'dberp_purchase_inquiry_items';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'inquiry_id',
        'purchase_request_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',
        'warehouse_id',
        'inquiry_quantity',
        'sort_order',
        'remark',
    ];

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

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

    public function inquiry(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseInquiry::class, 'inquiry_id');
    }

    public function purchaseRequestItem(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseRequestItem::class, 'purchase_request_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 warehouse(): BelongsTo
    {
        return $this->belongsTo(DberpWarehouse::class, 'warehouse_id');
    }

    public function quotes(): HasMany
    {
        return $this->hasMany(DberpPurchaseInquiryQuote::class, 'purchase_inquiry_item_id');
    }
}
