<?php

declare(strict_types=1);

namespace Numinix\SeekmodoWordPress\LocalIndex;

/**
 * Relevanssi-compatible hooks for migration (opt-in).
 */
final class RelevanssiCompat
{
    public static function register(): void
    {
        if (!VerticalConfig::relevanssiCompatEnabled()) {
            return;
        }
        if (!function_exists('add_filter')) {
            return;
        }

        add_filter('posts_pre_query', [self::class, 'postsPreQuery'], 9, 2);
    }

    /**
     * @param mixed $posts
     * @param mixed $query
     * @return mixed
     */
    public static function postsPreQuery($posts, $query)
    {
        if (!self::queryWantsLocalSearch($query)) {
            return $posts;
        }
        if (!LocalSearch::applyToQuery($query)) {
            return $posts;
        }
        if (!function_exists('get_posts') || !is_object($query) || !method_exists($query, 'query_vars')) {
            return null;
        }
        $posts = get_posts($query->query_vars);
        if (!is_array($posts)) {
            return [];
        }

        return $posts;
    }

    /**
     * @param mixed $query
     */
    public static function runQuery($query): void
    {
        if (!is_object($query) || !method_exists($query, 'get') || !method_exists($query, 'set')) {
            return;
        }
        if (!LocalSearch::applyToQuery($query)) {
            return;
        }
        if (method_exists($query, 'get_posts')) {
            $query->posts = $query->get_posts();
        }
    }

    /**
     * @param mixed $query
     */
    public static function queryWantsLocalSearch($query): bool
    {
        if (!is_object($query) || !method_exists($query, 'get')) {
            return false;
        }
        if (!VerticalConfig::shouldUseLocalIndex('content') && !VerticalConfig::shouldUseLocalIndex('commerce')) {
            return false;
        }
        $keyword = trim((string) $query->get('s'));
        if ($keyword === '') {
            return false;
        }
        if ($query->get('seekmodo') || $query->get('relevanssi')) {
            return true;
        }

        return false;
    }
}
