<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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');
    }
}
