<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\Search;

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

/**
 * Enhanced native content retrieval via WP_Query.
 */
final class WpContentRetriever
{
    /**
     * @return array{ids: list<int>, total: int}
     */
    public static function search(string $q, int $page, int $pageSize): array
    {
        if (!function_exists('get_posts')) {
            return ['ids' => [], 'total' => 0];
        }
        $posts = get_posts([
            's'                => $q,
            'post_type'        => PostTypeRegistry::indexable(),
            'post_status'      => 'publish',
            'posts_per_page'   => $pageSize,
            'paged'            => max(1, $page),
            'orderby'          => 'relevance',
            'suppress_filters' => false,
        ]);
        if (!is_array($posts)) {
            return ['ids' => [], 'total' => 0];
        }
        $ids = [];
        foreach ($posts as $p) {
            $ids[] = (int) ($p->ID ?? 0);
        }

        return ['ids' => array_values(array_filter($ids)), 'total' => count($ids)];
    }

    /**
     * @return list<array<string,mixed>>
     */
    public static function typeaheadRows(string $q, int $max): array
    {
        $r = self::search($q, 1, $max);

        return self::rowsFromIds($r['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;
    }
}
