<?php

namespace App\Domain\Pricing\Support;

/**
 * Percentages are stored as basis points (10% = 1000) so 12.5% is expressible.
 *
 * Humans never type basis points and never read them. Every conversion happens
 * here — the old bug was two authoring screens storing a plain percent into a
 * column the engine divided by 10000, making every discount 100x too small.
 */
final class Percent
{
    public const SCALE = 100;

    /** Human percent ("20", "12.5") -> stored basis points (2000, 1250). */
    public static function toBasisPoints(float|int|string $percent): int
    {
        return (int) round((float) $percent * self::SCALE);
    }

    /** Stored basis points (2000) -> human percent (20.0). */
    public static function fromBasisPoints(int $basisPoints): float
    {
        return round($basisPoints / self::SCALE, 2);
    }

    /** Display string, trimming a trailing ".0" — "20%" not "20.0%". */
    public static function label(int $basisPoints): string
    {
        $v = self::fromBasisPoints($basisPoints);

        return rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.') . '%';
    }
}
