<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model\Fetch;

/**
 * When the rows a format rejects make the whole feed unusable.
 */
class RejectedRows
{
    /** A few bad rows are left out; more than this share means a corrupt or wrong feed. */
    public const DEFAULT_MAX_SHARE = 0.1;

    /**
     * @throws InvalidFeedException
     */
    public static function check(int $accepted, int $rejected, float $maxShare, string $content): void
    {
        if ($rejected === 0) {
            return;
        }
        if ($accepted === 0) {
            throw InvalidFeedException::withSample(
                sprintf('Niciun rand nu are formatul asteptat (%d randuri respinse).', $rejected),
                $content
            );
        }
        $share = $rejected / ($accepted + $rejected);
        if ($share > $maxShare) {
            throw InvalidFeedException::withSample(sprintf(
                '%d din %d randuri (%d%%) nu au formatul asteptat, peste limita de %d%%: feed-ul nu este folosit.',
                $rejected,
                $accepted + $rejected,
                (int)round($share * 100),
                (int)round($maxShare * 100)
            ), $content);
        }
    }
}
