<?php

declare(strict_types=1);

namespace Tournament\Scoring;

final class PlacementTieBreaker implements TieBreaker
{
    /**
     * Resolve tie by placement.
     *
     * Lower placement number is better.
     *
     * Example:
     *
     * 1 beats 2
     * 2 beats 3
     * 3 beats 4
     */
    public function resolve(
        array $results
    ): ?int {
        $winnerId = null;
        $bestPlacement = null;

        foreach ($results as $result) {
            if (
                !isset($result['placement'])
                || $result['placement'] === null
            ) {
                return null;
            }

            $placement =
                (int) $result['placement'];

            if (
                $bestPlacement === null
                || $placement < $bestPlacement
            ) {
                $bestPlacement = $placement;

                $winnerId =
                    (int) $result['participant_id'];

                continue;
            }

            /*
             * Still tied.
             */
            if ($placement === $bestPlacement) {
                $winnerId = null;
            }
        }

        return $winnerId;
    }
}