<?php

namespace App\Support;

use App\Models\Lookups\UnitOfMeasure;

/**
 * Formats a quantity together with its unit of measure the same way
 * everywhere a quantity is shown — trailing zeros stripped (matching
 * InvoiceDocumentLine::quantityLabel()), unit code appended when known.
 */
final class Quantity
{
    public static function format(float|int|string|null $quantity, ?UnitOfMeasure $unit): string
    {
        $formatted = rtrim(rtrim(number_format((float) $quantity, 4, '.', ''), '0'), '.');
        $formatted = $formatted === '' ? '0' : $formatted;

        $label = self::unitLabel($unit);

        return $label !== null ? $formatted.' '.$label : $formatted;
    }

    public static function unitLabel(?UnitOfMeasure $unit): ?string
    {
        return $unit?->code ?? $unit?->name;
    }
}
