<?php

declare(strict_types=1);

namespace Numinix\SeekmodoSdk\Search;

/**
 * Merges pinned product/post IDs at the top of a result list.
 */
final class PinApplicator
{
    private FallbackBundle $bundle;

    public function __construct(FallbackBundle $bundle)
    {
        $this->bundle = $bundle;
    }

    /**
     * @param list<int> $ids
     * @return list<int>
     */
    public function apply(string $q, array $ids): array
    {
        $needle = mb_strtolower(trim($q));
        if ($needle === '') {
            return $ids;
        }

        $pins = $this->bundle->get()['pins'];
        $pinned = [];
        foreach ($pins as $row) {
            if (!is_array($row)) {
                continue;
            }
            $pinQ = mb_strtolower(trim((string) ($row['q'] ?? '')));
            if ($pinQ === '' || $pinQ !== $needle) {
                continue;
            }
            $productIds = $row['product_ids'] ?? [];
            if (!is_array($productIds)) {
                continue;
            }
            foreach ($productIds as $id) {
                $n = (int) $id;
                if ($n > 0) {
                    $pinned[] = $n;
                }
            }
        }

        if ($pinned === []) {
            return $ids;
        }

        $pinned = array_values(array_unique($pinned));
        $rest = [];
        $seen = array_flip($pinned);
        foreach ($ids as $id) {
            $n = (int) $id;
            if ($n > 0 && !isset($seen[$n])) {
                $rest[] = $n;
            }
        }

        return array_merge($pinned, $rest);
    }
}
