<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class SrcLimit implements Rule
{
    /* Goliath's accepted range for each unit of the per-source data-rate limit. */
    public const RANGES = [
        'pps'   => [ 100, 999000 ],
        'mbps'  => [ 1, 99900 ]
    ];

    private string $unit;

    public function __construct(string $_unit)
    {
        $this->unit = $_unit;
    }

    public function passes($attribute, $value)
    {

        if($value === null) {
            return true;
        }

        if(!is_int($value)) {
            return false;
        }

        [ $min, $max ] = self::RANGES[$this->unit];

        if($value < $min || $value > $max) {
            return false;
        }

        // Goliath keeps three significant digits and would quietly apply 12345 as 12300, so refuse what it would round.
        while($value >= 1000 && $value % 10 === 0) {
            $value = intdiv($value, 10);
        }

        return $value < 1000;

    }

    public function message()
    {
        [ $min, $max ] = self::RANGES[$this->unit];

        return "The :attribute must be null or a whole number from $min to $max with at most three significant digits, such as 12300 rather than 12345.";
    }
}
