<?php

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

use WP_Error;
use WP_REST_Response;
use WP_Query;
use stdClass;

/**
 * Search image attachments in the media library
 */
class Miruni_Search_Media_API extends Miruni_BaseAPI
{
    public static string $namespace = 'miruni/v1';
    public static string $route = '/search_media/';

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

    public static function setup(): void
    {
        add_action('rest_api_init', function () {
            register_rest_route(self::$namespace, self::$route, [
                'methods' => 'GET',
                'callback' => [__CLASS__, 'search_media'],
                'permission_callback' => [__CLASS__, 'snippet_secret_required_permission_callback'],
                'args' => [
                    'search' => [
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                        'description' => 'Search term matched against attachment titles (and default WP search fields).',
                    ],
                    'posts_per_page' => [
                        'required' => false,
                        'default' => 20,
                        'sanitize_callback' => 'absint',
                        'description' => 'Max number of attachments to return.',
                    ],
                    'mime_types' => [
                        'required' => false,
                        'sanitize_callback' => function ($value) {
                            if (empty($value))
                                return '';
                            if (is_array($value)) {
                                return array_map('sanitize_text_field', $value);
                            }
                            // comma separated string -> array
                            return array_map('sanitize_text_field', array_filter(array_map('trim', explode(',', (string) $value))));
                        },
                        'description' => 'Optional list (array or comma separated string) of mime types (e.g. image/jpeg,image/png). Defaults to images only.',
                    ],
                ],
            ]);
        });
    }

    /**
     * Perform media search.
     * @param \WP_REST_Request<array<mixed>> $request
     * @return WP_Error|WP_REST_Response
     */
    public static function search_media(\WP_REST_Request $request): WP_Error|WP_REST_Response
    {
        $search = $request->get_param('search');
        $posts_per_page = $request->get_param('posts_per_page') ?: 20;
        $mime_types = $request->get_param('mime_types');

        // Default to common image mime types if none provided
        if (empty($mime_types)) {
            $mime_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
        }

        $query_args = [
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'post_mime_type' => $mime_types,
            'posts_per_page' => $posts_per_page,
            's' => $search,
            'orderby' => 'date',
            'order' => 'DESC',
            'fields' => 'all', // we need full WP_Post objects
        ];

        $media_query = new WP_Query($query_args);
        $attachment_posts = $media_query->get_posts();

        $response_attachments = [];
        foreach ($attachment_posts as $attachment) {
            if (is_int($attachment)) {
                continue; // Should not happen with fields=all but keep pattern consistent
            }
            $response_attachments[$attachment->ID] = $attachment;
        }

        $response_data = [
            'attachments' => (object) $response_attachments,
            'search_params' => [
                'search' => $search,
                'posts_per_page' => $posts_per_page,
                'mime_types' => $mime_types,
            ],
            'found_attachments' => count($response_attachments),
        ];

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

