<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

use GriffinForms\Includes\CommandPalette\FormOptionsRegistry;
use GriffinForms\Includes\CommandPalette\SearchProviderInterface;
use GriffinForms\Includes\CommandPalette\SearchResultItem;

class FormOptionsProvider implements SearchProviderInterface
{
    public function getProviderId(): string { return 'form_options'; }
    public function getLabel(): string      { return 'Form Options'; }
    public function getPriority(): int      { return 50; }
    public function getQuickItems(int $form_id): array { return []; }

    public function query(string $query, int $form_id): array
    {
        if ($query === '') {
            return [];
        }

        try {
            $entries = FormOptionsRegistry::getInstance()->search($query);
        } catch (\Throwable $e) {
            return [];
        }

        $results = [];

        foreach ($entries as $entry) {
            $description = strlen($entry['description']) > 80
                ? substr($entry['description'], 0, 77) . '…'
                : $entry['description'];

            $results[] = new SearchResultItem(
                result_id:      'formoption_' . $entry['option_id'],
                provider_id:    $this->getProviderId(),
                label:          $entry['label'],
                action_type:    'open_modal_with_context',
                action_payload: [
                    'modal_id' => 'griffinforms-builder-modal-formoptions',
                    'context'  => [
                        'tab'    => $entry['tab'],
                        'anchor' => 'gf-formoptions-' . $entry['option_id'] . '-row',
                    ],
                ],
                description:    $description,
                icon:           'option',
                score:          0
            );
        }

        return $results;
    }
}
