<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\LocalIndex;

use Numinix\SeekmodoWordPress\Content\PostTypeRegistry;
use Numinix\SeekmodoWordPress\Content\ThumbnailUrl;

/**
 * Local inverted-index retrieval for Enhanced Native.
 */
final class LocalIndexRetriever
{
    /**
     * @param array<string,mixed> $constraints
     * @return array{ids: list<int>, total: int}
     */
    public static function search(string $q, int $page, int $pageSize, array $constraints = []): array
    {
        if (!VerticalConfig::shouldUseLocalIndex('content')) {
            return ['ids' => [], 'total' => 0];
        }
        if (!isset($constraints['post_type'])) {
            $constraints['post_type'] = PostTypeRegistry::indexable();
        }
        $result = SearchEngine::search($q, $page, $pageSize, $constraints, 'content');

        return ['ids' => $result['ids'], 'total' => $result['total']];
    }

    /**
     * @param array<string,mixed> $constraints
     * @return array{ids: list<int>, total: int}
     */
    public static function searchProducts(string $q, int $page, int $pageSize, array $constraints = []): array
    {
        if (!VerticalConfig::shouldUseLocalIndex('commerce')) {
            return ['ids' => [], 'total' => 0];
        }
        $constraints['post_type'] = 'product';
        $result = SearchEngine::search($q, $page, $pageSize, $constraints, 'commerce');

        return ['ids' => $result['ids'], 'total' => $result['total']];
    }

    /**
     * @return list<array<string,mixed>>
     */
    public static function typeaheadRows(string $q, int $max, string $vertical = 'content'): array
    {
        $ids = SearchEngine::typeahead($q, $max, $vertical);

        return self::rowsFromIds($ids, $max);
    }

    /**
     * @param list<int> $ids
     * @return list<array<string,mixed>>
     */
    public static function rowsFromIds(array $ids, int $max): array
    {
        if (!function_exists('get_post')) {
            return [];
        }
        $out = [];
        foreach ($ids as $id) {
            if (count($out) >= $max) {
                break;
            }
            $post_id = (int) $id;
            if ($post_id <= 0) {
                continue;
            }
            $p = get_post($post_id);
            if (!$p) {
                continue;
            }
            $out[] = [
                'id'            => (string) $post_id,
                'title'         => (string) ($p->post_title ?? ''),
                'permalink'     => function_exists('get_permalink') ? (string) get_permalink($post_id) : '',
                'thumbnail_url' => ThumbnailUrl::forPost($post_id),
                'post_type'     => (string) ($p->post_type ?? 'post'),
                'excerpt'       => (string) ($p->post_excerpt ?? ''),
            ];
        }

        return $out;
    }
}
