<?php
namespace App\Controllers\PSI;

use App\Models\PSI\Material;
use App\Models\PSI\Product;
use App\Models\PSI\StockMove;

/**
 * 库存台账统一维护：任何出入库都经此更新，保证物料/成品库存与流水一致。
 * item_type: material | product
 */
trait StockHelper
{
    private function adjustStock(string $itemType, int $itemId, float $qty, string $direction, string $refNo, string $batchNo = ''): void
    {
        $model = $itemType === 'product' ? new Product() : new Material();
        $item = $model->find($itemId);
        if (!$item) return;
        $cur = (float)($item['stock'] ?? 0);
        $new = $direction === 'in' ? $cur + $qty : max(0, $cur - $qty);
        $model->update($itemId, ['stock' => $new]);
        (new StockMove())->insert([
            'item_type'  => $itemType,
            'item_id'    => $itemId,
            'direction'  => $direction,
            'qty'        => $qty,
            'ref_no'     => $refNo,
            'batch_no'   => $batchNo,
            'remark'     => '',
            'created_at' => date('Y-m-d'),
        ]);

        // 低库存预警：仅当出库且跌破阈值时触发（避免重复骚扰）
        $threshold = \Core\Notify::lowStockThreshold();
        if (\Core\Notify::lowStockEnabled()
            && $direction === 'out'
            && $new <= $threshold
            && $cur > $threshold) {
            \Core\Notify::lowStockEvent($itemType, $item['name'] ?? '', $new, $threshold, $itemId);
        }
    }
}
