<?php
/**
 * GGM Commerce MCP REST API
 *
 * WordPress REST API endpoint handler for Model Context Protocol requests
 * Provides the external interface for AI assistants to communicate with the plugin
 *
 * @package GGM_Commerce
 * @since 1.0.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class GGM_Commerce_MCP_REST_API {

    /**
     * API namespace
     * @var string
     */
    private $namespace = 'mcp/v1';

    /**
     * MCP server instance
     * @var GGM_Commerce_MCP_Server
     */
    private $server;

    /**
     * Auth handler instance
     * @var GGM_Commerce_MCP_Auth
     */
    private $auth;

    /**
     * Constructor
     */
    public function __construct() {
        // Load dependencies
        require_once plugin_dir_path(__FILE__) . 'class-mcp-server.php';
        require_once plugin_dir_path(__FILE__) . 'mcp/class-mcp-auth.php';

        $this->server = GGM_Commerce_MCP_Server::get_instance();
        $this->auth = new GGM_Commerce_MCP_Auth();

        // Register all resources, tools, and prompts
        $this->register_mcp_components();

        // Register routes directly since we're already inside rest_api_init
        $this->register_routes();
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        register_rest_route($this->namespace, '/mcp', [
            [
                'methods' => ['GET', 'POST'],
                'callback' => [$this, 'handle_mcp_request'],
                'permission_callback' => [$this, 'authenticate_request'],
                'args' => []
            ]
        ]);

        // Health check endpoint (no auth required)
        register_rest_route($this->namespace, '/health', [
            'methods' => 'GET',
            'callback' => [$this, 'health_check'],
            'permission_callback' => '__return_true'
        ]);
    }

    /**
     * Handle MCP request
     *
     * @param WP_REST_Request $request WordPress REST request
     * @return WP_REST_Response|WP_Error
     */
    public function handle_mcp_request($request) {
        try {
            // Get request body
            $body = $request->get_json_params();

            if (empty($body)) {
                return new WP_Error(
                    'invalid_json',
                    'Invalid JSON in request body',
                    ['status' => 400]
                );
            }

            // Process through MCP server
            $response = $this->server->handle_request($body);

            // Return JSON-RPC response
            return rest_ensure_response($response);

        } catch (Exception $e) {

            return new WP_Error(
                'mcp_server_error',
                $e->getMessage(),
                ['status' => 500]
            );
        }
    }

    /**
     * Authenticate request
     *
     * @param WP_REST_Request $request WordPress REST request
     * @return bool|WP_Error
     */
    public function authenticate_request($request) {
        return $this->auth->authenticate_request($request);
    }

    /**
     * Health check endpoint
     *
     * @return WP_REST_Response
     */
    public function health_check() {
        return rest_ensure_response([
            'status' => 'ok',
            'service' => 'ggm-commerce-mcp',
            'version' => '1.0.0',
            'timestamp' => current_time('mysql')
        ]);
    }

    /**
     * Register all MCP components (resources, tools, prompts)
     */
    private function register_mcp_components() {
        // Load MCP component classes
        $mcp_dir = plugin_dir_path(__FILE__) . 'mcp/';

        $component_files = [
            'class-product-resources.php',
            'class-order-resources.php',
            'class-customer-resources.php',
            'class-cart-tools.php',
            'class-product-tools.php',
            'class-product-management-tools.php',
            'class-order-tools.php',
            'class-inventory-tools.php',
            'class-media-tools.php',
            'class-attribute-tools.php',
            'class-variation-tools.php',
            'class-taxonomy-tools.php',
            'class-customer-tools.php',
            'class-shipment-tools.php',
            'class-review-tools.php',
            'class-export-tools.php',
            'class-export-resources.php',
            'class-discount-tools.php',
            'class-discount-resources.php',
            'class-shopping-prompts.php'
        ];

        foreach ($component_files as $file) {
            $file_path = $mcp_dir . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            }
        }

        // Initialize component classes
        if (class_exists('GGM_Commerce_Product_Resources')) {
            new GGM_Commerce_Product_Resources($this->server);
        }

        if (class_exists('GGM_Commerce_Order_Resources')) {
            new GGM_Commerce_Order_Resources($this->server);
        }

        if (class_exists('GGM_Commerce_Customer_Resources')) {
            new GGM_Commerce_Customer_Resources($this->server);
        }

        if (class_exists('GGM_Commerce_Cart_Tools')) {
            new GGM_Commerce_Cart_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Product_Tools')) {
            new GGM_Commerce_Product_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Product_Management_Tools')) {
            new GGM_Commerce_Product_Management_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Order_Tools')) {
            new GGM_Commerce_Order_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Inventory_Tools')) {
            new GGM_Commerce_Inventory_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Media_Tools')) {
            new GGM_Commerce_Media_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Attribute_Tools')) {
            new GGM_Commerce_Attribute_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Variation_Tools')) {
            new GGM_Commerce_Variation_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Taxonomy_Tools')) {
            new GGM_Commerce_Taxonomy_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Customer_Tools')) {
            new GGM_Commerce_Customer_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Shipment_Tools')) {
            new GGM_Commerce_Shipment_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_Review_Tools')) {
            new GGM_Commerce_Review_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_MCP_Export_Tools')) {
            new GGM_Commerce_MCP_Export_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_MCP_Export_Resources')) {
            new GGM_Commerce_MCP_Export_Resources($this->server);
        }

        if (class_exists('GGM_Commerce_MCP_Discount_Tools')) {
            new GGM_Commerce_MCP_Discount_Tools($this->server);
        }

        if (class_exists('GGM_Commerce_MCP_Discount_Resources')) {
            new GGM_Commerce_MCP_Discount_Resources($this->server);
        }

        if (class_exists('GGM_Commerce_Shopping_Prompts')) {
            new GGM_Commerce_Shopping_Prompts($this->server);
        }
    }
}
