<?php

namespace GriffinForms\Includes\CommandPalette;

class KeywordMap
{
    private array $entries = [];

    public function register(string $keyword, string $action_type, array $action_payload, string $label = '', string $description = '', string $icon = 'keyword'): void
    {
        $this->entries[] = [
            'keyword'        => strtolower($keyword),
            'label'          => $label ?: $keyword,
            'description'    => $description,
            'action_type'    => $action_type,
            'action_payload' => $action_payload,
            'icon'           => $icon,
        ];
    }

    /** @return SearchResultItem[] */
    public function search(string $query): array
    {
        if ($query === '') {
            return [];
        }

        $q       = strtolower($query);
        $results = [];
        $seen    = [];

        foreach ($this->entries as $entry) {
            if (stripos($entry['keyword'], $q) === false) {
                continue;
            }

            $key = $entry['label'] . '|' . $entry['action_type'] . '|' . json_encode($entry['action_payload']);
            if (isset($seen[$key])) {
                continue;
            }
            $seen[$key] = true;

            $results[] = new SearchResultItem(
                result_id:      'keyword_' . md5($key),
                provider_id:    'builder_keywords',
                label:          $entry['label'],
                action_type:    $entry['action_type'],
                action_payload: $entry['action_payload'],
                description:    $entry['description'],
                icon:           $entry['icon'] ?? 'keyword',
                score:          0
            );
        }

        return $results;
    }
}
