<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\Rotation;

/**
 * Weighted-random rotation. Each rotation row has an integer `weight`;
 * the pick probability is proportional to weight / total_weight.
 */
class WeightedRandom implements RotationStrategy
{
    /**
     * Picks a rotation row at random, weighted by each row's `weight`.
     *
     * @param  integer                          $linkId    Link ID being rotated (unused; weighting is stateless).
     * @param  array<int, array<string, mixed>> $rotations Rows from prli_link_rotations.
     * @return array<string, mixed>|null
     */
    public function pick(int $linkId, array $rotations): ?array
    {
        unset($linkId);
        if (!$rotations) {
            return null;
        }

        $total = 0;
        foreach ($rotations as $row) {
            $total += max(0, (int) ($row['weight'] ?? 1));
        }
        if ($total <= 0) {
            return null;
        }

        $roll = random_int(1, $total);
        $acc  = 0;
        foreach ($rotations as $row) {
            $acc += max(0, (int) ($row['weight'] ?? 1));
            if ($roll <= $acc) {
                return $row;
            }
        }

        // Unreachable unless all weights are 0 (filtered above) — defensive.
        $last = end($rotations);
        return is_array($last) ? $last : null;
    }
}
