<?php
/**
 * Confronts a submitted line selection with what the rules actually allow.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Core;

/**
 * What arrives from a form is a proposal, never a fact. Quantities are clamped
 * to what the server computed as available, ineligible lines are dropped no
 * matter what was posted, and unknown identifiers are ignored.
 */
final class LineSelection
{
    /**
     * @param array<int,array<string,mixed>> $evaluatedLines Output of EligibilityRules.
     * @param array<int|string,mixed>        $posted         item id => quantity.
     *
     * @return array<int,array<string,mixed>>
     */
    public static function resolve(array $evaluatedLines, array $posted): array
    {
        $selected = [];

        foreach ($evaluatedLines as $line) {
            if (true !== ($line['eligible'] ?? false)) {
                continue;
            }

            $itemId = (int) ($line['item_id'] ?? 0);

            if (!array_key_exists($itemId, $posted)) {
                continue;
            }

            $available = (int) ($line['available'] ?? 0);
            $wanted    = (int) $posted[$itemId];

            if ($wanted < 1 || $available < 1) {
                continue;
            }

            $selected[] = [
                'item_id'      => $itemId,
                'product_id'   => (int) ($line['product_id'] ?? 0),
                'variation_id' => (int) ($line['variation_id'] ?? 0),
                'name'         => (string) ($line['name'] ?? ''),
                'sku'          => (string) ($line['sku'] ?? ''),
                'qty'          => min($wanted, $available),
            ];
        }

        return $selected;
    }
}
