<?php

declare(strict_types=1);

namespace Tournament\Scoring;

final class KillsTieBreaker implements TieBreaker
{
    /**
     * Resolve tie by kills.
     *
     * Participant with more kills wins.
     */
    public function resolve(
        array $results
    ): ?int {
        $winnerId = null;
        $highestKills = null;

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

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

            if (
                $highestKills === null
                || $kills > $highestKills
            ) {
                $highestKills = $kills;
                $winnerId =
                    (int) $result['participant_id'];

                continue;
            }

            /*
             * Still tied.
             */
            if ($kills === $highestKills) {
                $winnerId = null;
            }
        }

        return $winnerId;
    }
}