<?php

namespace Miruni\RestApi;
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

use WP_Error;
use WP_REST_Response;
use WP_Query;

class Miruni_Search_Posts_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/search_posts/';

    public static function get_rest_url(): string
    {
        return self::_get_rest_url([]);
    }

    public static function setup(): void
    {
        // Register REST API endpoint
        add_action('rest_api_init', function () {
            register_rest_route(self::$namespace, self::$route, [
                'methods' => 'GET',
                'callback' => [__CLASS__, 'search_posts'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
                'args' => [
                    'search' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                        'description' => 'Search term to match against post titles',
                    ],
                    'posts_per_page' => [
                        'required' => false,
                        'default' => 10,
                        'sanitize_callback' => 'absint',
                        'description' => 'Number of posts to return',
                    ],
                ],
            ]);
        });
    }

    /**
     * Search posts by title or content
     * 
     * @param \WP_REST_Request<array<mixed>> $request The REST API request
     * @return WP_Error|WP_REST_Response Response object or error
     */
    public static function search_posts(\WP_REST_Request $request): WP_Error|WP_REST_Response
    {
        $search = $request->get_param('search');
        $posts_per_page = $request->get_param('posts_per_page') ?: 20;


        // Use WP_Query with search functionality
        $search_query = new WP_Query([
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => $posts_per_page,
            's' => $search, // Use WordPress built-in search

        ]);

        // If we need more specific title/content matching, use a custom approach
        $post_objects = $search_query->get_posts();

        // Format response to match context-api format
        $response_posts = [];
        foreach ($post_objects as $post) {
            if (is_int($post)) {
                continue; // Skip if not a valid WP_Post object
            }
            $response_posts[$post->ID] = $post;
        }

        $response_data = [
            'posts' => $response_posts,
            'search_params' => [
                'search' => $search,
                'posts_per_page' => $posts_per_page
            ],
            'found_posts' => count($response_posts)
        ];

        return new WP_REST_Response($response_data, 200);
    }
}
