<?php

declare(strict_types=1);

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

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpInventoryBalance extends Model
{
    protected $table = 'dberp_inventory_balances';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'product_id',
        'product_sku_id',
        'warehouse_id',
        'realtime_quantity',
        'available_quantity',
        'occupied_quantity',
        'safety_stock',
        'last_moved_at',
    ];

    protected function casts(): array
    {
        return [
            'product_id' => 'integer',
            'product_sku_id' => 'integer',
            'warehouse_id' => 'integer',
            'realtime_quantity' => 'decimal:4',
            'available_quantity' => 'decimal:4',
            'occupied_quantity' => 'decimal:4',
            'safety_stock' => 'decimal:4',
            'last_moved_at' => 'datetime',
        ];
    }

    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 scopeLowStock(Builder $query): Builder
    {
        return $query
            ->where('safety_stock', '>', 0)
            ->whereColumn('available_quantity', '<=', 'safety_stock');
    }

    public function scopeZeroStock(Builder $query): Builder
    {
        return $query->where('realtime_quantity', '<=', 0);
    }
}
