<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\DberpProduct;

/**
 * 库存结余列表：按当前商品档案将主计量结余折算为辅助单位数量，仅作参考展示。
 */
final class DberpInventoryBalanceAuxiliaryDisplay
{
    public static function approximateAuxiliaryQuantity(?DberpProduct $product, mixed $realtimeBaseQuantity): string
    {
        if (! $product instanceof DberpProduct || ! (bool) $product->is_auxiliary_unit_enabled) {
            return '—';
        }

        $baseQtyStr = self::normalizeNumericString($product->base_unit_quantity);
        $auxQtyStr = self::normalizeNumericString($product->auxiliary_unit_quantity);
        $stockStr = self::normalizeNumericString($realtimeBaseQuantity);

        if ($baseQtyStr === null || $auxQtyStr === null || $stockStr === null) {
            return '—';
        }

        if (bccomp($baseQtyStr, '0', 8) !== 1 || bccomp($auxQtyStr, '0', 8) !== 1) {
            return '—';
        }

        if (bccomp($stockStr, '0', 8) !== 1) {
            return '—';
        }

        $auxName = trim((string) ($product->relationLoaded('auxiliaryUnit') ? $product->auxiliaryUnit?->name : $product->auxiliaryUnit()->value('name')));
        if ($auxName === '') {
            return '—';
        }

        $ratio = bcdiv($auxQtyStr, $baseQtyStr, 12);
        $approx = bcmul($stockStr, $ratio, 8);
        $approxTrimmed = rtrim(rtrim($approx, '0'), '.');

        return DberpNumberFormatter::quantity($approxTrimmed).' '.$auxName;
    }

    private static function normalizeNumericString(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        $string = is_string($value) ? trim($value) : trim((string) $value);
        if ($string === '' || ! is_numeric($string)) {
            return null;
        }

        return $string;
    }
}
