<?php

declare(strict_types=1);

namespace Numinix\SeekmodoSdk\Search;

/**
 * Injects rescue / bestseller IDs when native retrieval returns empty.
 */
final class ZeroResultRescue
{
    private FallbackBundle $bundle;

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

    /**
     * @param list<int> $ids
     * @return list<int>
     */
    public function rescue(string $q, array $ids): array
    {
        if ($ids !== []) {
            return $ids;
        }

        $needle = mb_strtolower(trim($q));
        $bundle = $this->bundle->get();

        foreach ($bundle['rescue'] as $row) {
            if (!is_array($row)) {
                continue;
            }
            $pattern = mb_strtolower(trim((string) ($row['q_pattern'] ?? '')));
            if ($pattern === '' || $pattern !== $needle) {
                continue;
            }
            $ids = $this->intList($row['product_ids'] ?? []);
            if ($ids !== []) {
                return $ids;
            }
        }

        return $this->intList($bundle['bestsellers']);
    }

    /**
     * @param mixed $raw
     * @return list<int>
     */
    private function intList(mixed $raw): array
    {
        if (!is_array($raw)) {
            return [];
        }
        $out = [];
        foreach ($raw as $id) {
            $n = (int) $id;
            if ($n > 0) {
                $out[] = $n;
            }
        }

        return array_values(array_unique($out));
    }
}
