<?php

declare(strict_types=1);

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

namespace App\Business\Inventory;

use App\Models\DberpInventoryBalance;
use Illuminate\Database\Eloquent\Builder;

final class InventoryWarningService
{
    public function __construct(
        private readonly InventoryRuleService $ruleService,
    ) {}

    public function query(): Builder
    {
        return DberpInventoryBalance::query()
            ->with(['product.category', 'warehouse'])
            ->where(function (Builder $query): void {
                $query->zeroStock();

                if ($this->ruleService->safetyStockAlertEnabled()) {
                    $query->orWhere(function (Builder $subQuery): void {
                        $subQuery->lowStock();
                    });
                }
            });
    }

    public function warningType(DberpInventoryBalance $balance): string
    {
        if ((float) $balance->realtime_quantity <= 0) {
            return 'zero_stock';
        }

        if (
            $this->ruleService->safetyStockAlertEnabled()
            && (float) $balance->safety_stock > 0
            && (float) $balance->available_quantity <= (float) $balance->safety_stock
        ) {
            return 'low_stock';
        }

        return 'normal';
    }

    public function warningTypeLabel(DberpInventoryBalance $balance): string
    {
        return __('dberp.options.inventory_warning_type.'.$this->warningType($balance));
    }
}