<?php

namespace GriffinForms\Includes\CommandPalette\Providers;

use GriffinForms\Includes\CommandPalette\SearchProviderInterface;
use GriffinForms\Includes\CommandPalette\SearchResultItem;
use GriffinForms\Includes\Integrations\Providers;

class IntegrationsProvider implements SearchProviderInterface
{
    public function getProviderId(): string { return 'integrations'; }
    public function getLabel(): string      { return 'Integrations'; }
    public function getPriority(): int      { return 30; }
    public function getQuickItems(int $form_id): array { return []; }

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

        try {
            $providers = Providers::getInstance()->getAllIncludingPaidBlocked();
        } catch (\Throwable $e) {
            return [];
        }

        $results = [];

        foreach ($providers as $provider) {
            $name = (string) ($provider['name'] ?? '');
            $id   = (string) ($provider['id']   ?? '');

            if ($name === '' || $id === '') {
                continue;
            }

            if (stripos($name, $query) === false) {
                continue;
            }

            $raw_desc = (string) ($provider['description'] ?? '');
            if (strlen($raw_desc) > 80) {
                $raw_desc = substr($raw_desc, 0, 80) . '…';
            }
            if (!empty($provider['is_paid'])) {
                $suffix   = __('Pro', 'griffinforms-form-builder');
                $raw_desc = $raw_desc ? $raw_desc . ' · ' . $suffix : $suffix;
            } elseif (!empty($provider['coming_soon'])) {
                $suffix   = __('Coming Soon', 'griffinforms-form-builder');
                $raw_desc = $raw_desc ? $raw_desc . ' · ' . $suffix : $suffix;
            }
            $description = $raw_desc;

            $results[] = new SearchResultItem(
                result_id:      'integration_' . $id,
                provider_id:    $this->getProviderId(),
                label:          $name,
                action_type:    'open_modal_with_context',
                action_payload: [
                    'modal_id' => 'griffinforms-builder-modal-integrations',
                    'context'  => ['provider_id' => $id],
                ],
                description:    $description,
                icon:           (string) ($provider['icon'] ?? 'integration'),
                score:          0
            );
        }

        return $results;
    }
}
