<?php

declare(strict_types=1);

namespace PpPhp\Core\IconManager;

final class IconSearch
{
    /**
     * @param IconDefinition[] $icons
     * @return IconDefinition[]
     */
    public static function search(array $icons, string $query, int $limit = 100): array
    {
        $query = mb_strtolower(trim($query));

        if ($query === '') {
            return array_slice($icons, 0, $limit);
        }

        $results = [];

        foreach ($icons as $icon) {

            $haystack = mb_strtolower(
                implode(' ', array_merge(
                    [
                        $icon->name,
                        $icon->label,
                        $icon->className,
                        $icon->style
                    ],
                    $icon->categories,
                    $icon->aliases,
                    $icon->keywords
                ))
            );

            if (str_contains($haystack, $query)) {
                $results[] = $icon;
            }

            if (count($results) >= $limit) {
                break;
            }
        }

        return $results;
    }
}
