<?php

namespace GriffinForms\Includes\CommandPalette;

use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class PaletteRest
{
    public const NAMESPACE = 'griffinforms/v1';

    public function __construct()
    {
        add_action('rest_api_init', [$this, 'registerRoutes']);
    }

    public function registerRoutes(): void
    {
        register_rest_route(self::NAMESPACE, '/palette/query', [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'handleQuery'],
            'permission_callback' => [$this, 'checkPermission'],
            'args'                => [
                'query'   => [
                    'type'              => 'string',
                    'default'           => '',
                    'sanitize_callback' => 'sanitize_text_field',
                ],
                'form_id' => [
                    'type'              => 'integer',
                    'default'           => 0,
                    'sanitize_callback' => 'absint',
                ],
            ],
        ]);

        register_rest_route(self::NAMESPACE, '/palette/quick', [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'handleQuick'],
            'permission_callback' => [$this, 'checkPermission'],
            'args'                => [
                'form_id' => [
                    'type'              => 'integer',
                    'default'           => 0,
                    'sanitize_callback' => 'absint',
                ],
            ],
        ]);
    }

    public function checkPermission(): bool
    {
        return current_user_can('manage_options');
    }

    public function handleQuery(WP_REST_Request $request): WP_REST_Response
    {
        $query   = (string) $request->get_param('query');
        $form_id = (int) $request->get_param('form_id');

        $registry = SearchProviderRegistry::getInstance();
        $items    = $registry->query($query, $form_id);

        return new WP_REST_Response($this->serializeItems($items), 200);
    }

    public function handleQuick(WP_REST_Request $request): WP_REST_Response
    {
        $form_id = (int) $request->get_param('form_id');

        $registry = SearchProviderRegistry::getInstance();
        $items    = $registry->getQuickItems($form_id);

        return new WP_REST_Response($this->serializeItems($items), 200);
    }

    private function serializeItems(array $items): array
    {
        return array_values(array_map(function (SearchResultItem $item) {
            return $item->toArray();
        }, $items));
    }
}
