/**
 * MCP SSE Server for WooCommerce
 *
 * Provides MCP tools for accessing WooCommerce orders and customers data
 * using Server-Sent Events (SSE) protocol for n8n integration.
 *
 * Authentication: Internal API keys from internal_api_keys table
 * Required parameter: shop_id (store ID from stores table)
 * Protocol: MCP over HTTP with SSE (2024-11-05)
 */

import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import {
  requireInternalApiKey,
  createInternalApiKeyErrorResponse
} from '../_shared/internal-api-key-auth.ts';
import {
  fetchProducts,
  fetchOrders,
  fetchOrder,
  fetchCustomers,
  WooCommerceOrder,
  WooCommerceCustomer,
  WooCommerceOrderFilters,
  WooCommerceCustomerFilters
} from '../_shared/woocommerce-client.ts';
import {
  McpTool,
  LlmCustomer,
  LlmOrder,
  LlmProduct
} from '../_shared/mcp-types.ts';
import {
  createMcpErrorResponse,
  createMcpSuccessResponse,
  validateParams,
  cleanResponseData
} from '../_shared/mcp-helpers.ts';
import {
  getStoreQdrantConfig,
  queryQdrantProducts,
  queryQdrantOrders,
  queryQdrantCustomers,
  queryQdrantCustomContent
} from '../_shared/mcp-qdrant-helpers.ts';
import {
  getAccessPolicyConfig,
  validateAccess,
  isSyncAllowed,
  isApiOnlyMode,
  getDataTypePolicy,
  createApiOnlyNotice
} from '../_shared/access-policy-helpers.ts';
import {
  JsonRpcRequest,
  createSseResponse,
  sendSseMessage,
  closeSseStream,
  parseJsonRpcRequest,
  createJsonRpcSuccess,
  createJsonRpcError,
  createInitializeResult,
  validateInitializeParams,
  validateToolCallParams,
  ToolCallParams,
  ToolCallResult,
  JsonRpcErrorCode
} from '../_shared/mcp-sse.ts';

// Initialize Supabase client
const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
const supabase = createClient(supabaseUrl, supabaseServiceKey);

const SERVER_NAME = 'mcp-woocommerce';
const SERVER_VERSION = '3.0.0';

// MCP Tool Definitions
const TOOLS: McpTool[] = [
  {
    name: 'woocommerce_get_products',
    description: 'Get products from a WooCommerce store with filtering. Returns product catalog with details like name, SKU, price, and status. Use this to search for products or browse the catalog. Limited to 20 results maximum.',
    inputSchema: {
      type: 'object',
      properties: {
        shop_id: {
          type: 'string',
          description: 'The UUID of the WooCommerce store from the stores table'
        },
        sku: {
          type: 'string',
          description: 'Filter by product SKU (exact match)'
        },
        name: {
          type: 'string',
          description: 'Filter by product name (partial match, case-insensitive)'
        },
        status: {
          type: 'string',
          description: 'Filter by product status (publish, draft, pending)'
        },
        min_price: {
          type: 'number',
          description: 'Minimum price filter'
        },
        max_price: {
          type: 'number',
          description: 'Maximum price filter'
        },
        limit: {
          type: 'number',
          description: 'Number of products to return (default: 10, max: 20)'
        }
      },
      required: ['shop_id']
    }
  },
  {
    name: 'woocommerce_get_order',
    description: 'Get a specific order from a WooCommerce store by order ID or order number. Returns complete order details including customer info, items, status, and totals. Use this when a customer provides their order number.',
    inputSchema: {
      type: 'object',
      properties: {
        shop_id: {
          type: 'string',
          description: 'The UUID of the WooCommerce store from the stores table'
        },
        order_id: {
          type: 'number',
          description: 'The WooCommerce order ID (numeric)'
        }
      },
      required: ['shop_id', 'order_id']
    }
  },
  {
    name: 'woocommerce_list_orders',
    description: 'List orders from a WooCommerce store with filtering. At least one filter is REQUIRED (created_after, created_before, updated_after, updated_before, customer_email, or customer_name). Returns order details including customer info, items, status, and totals. Limited to 20 results maximum.',
    inputSchema: {
      type: 'object',
      properties: {
        shop_id: {
          type: 'string',
          description: 'The UUID of the WooCommerce store from the stores table'
        },
        created_after: {
          type: 'string',
          description: 'Filter orders created after this ISO 8601 datetime (e.g., 2025-01-01T00:00:00Z)'
        },
        created_before: {
          type: 'string',
          description: 'Filter orders created before this ISO 8601 datetime'
        },
        updated_after: {
          type: 'string',
          description: 'Filter orders updated after this ISO 8601 datetime'
        },
        updated_before: {
          type: 'string',
          description: 'Filter orders updated before this ISO 8601 datetime'
        },
        customer_email: {
          type: 'string',
          description: 'Filter by customer email address'
        },
        customer_name: {
          type: 'string',
          description: 'Filter by customer name (searches billing name)'
        },
        status: {
          type: 'string',
          description: 'Filter by order status: any, pending, processing, on-hold, completed, cancelled, refunded, failed'
        },
        limit: {
          type: 'number',
          description: 'Number of orders to return (default: 5, max: 20)'
        }
      },
      required: ['shop_id']
    }
  },
  {
    name: 'woocommerce_get_customer',
    description: 'Get a specific customer from a WooCommerce store by email address. Returns a single customer with contact info, order count, and total spent. Email parameter is REQUIRED.',
    inputSchema: {
      type: 'object',
      properties: {
        shop_id: {
          type: 'string',
          description: 'The UUID of the WooCommerce store from the stores table'
        },
        email: {
          type: 'string',
          description: 'The customer email address (required)'
        }
      },
      required: ['shop_id', 'email']
    }
  },
  {
    name: 'woocommerce_search_custom_content',
    description: 'Search custom knowledge base (uploaded PDFs and text entries) for relevant information using semantic search. Returns matching content with titles, excerpts, and relevance scores. Use this to find custom documentation, policies, FAQs, or any store-specific information that has been uploaded.',
    inputSchema: {
      type: 'object',
      properties: {
        shop_id: {
          type: 'string',
          description: 'The UUID of the WooCommerce store from the stores table'
        },
        query: {
          type: 'string',
          description: 'The search query to find relevant content'
        },
        limit: {
          type: 'number',
          description: 'Number of results to return (default: 5, max: 10)'
        }
      },
      required: ['shop_id', 'query']
    }
  }
];

/**
 * Convert WooCommerce customer to LLM-friendly format
 */
function formatCustomerForLlm(customer: WooCommerceCustomer): LlmCustomer {
  return {
    id: customer.id.toString(),
    name: `${customer.first_name} ${customer.last_name}`.trim(),
    email: customer.email,
    phone: customer.billing?.phone || undefined,
    ordersCount: customer.orders_count,
    totalSpent: customer.total_spent ? `${customer.total_spent}` : undefined
  };
}

/**
 * Convert WooCommerce order to LLM-friendly format
 */
function formatOrderForLlm(order: WooCommerceOrder): LlmOrder {
  return {
    id: order.id.toString(),
    orderNumber: order.number,
    customer: {
      name: `${order.billing.first_name} ${order.billing.last_name}`.trim(),
      email: order.billing.email,
      phone: order.billing.phone || undefined
    },
    status: order.status,
    total: order.total,
    currency: order.currency,
    items: order.line_items.map(item => ({
      name: item.name,
      quantity: item.quantity,
      price: item.total
    })),
    createdAt: order.date_created
  };
}

/**
 * Handle woocommerce_get_products tool
 */
async function handleGetProducts(args: Record<string, any>): Promise<ToolCallResult> {
  const { shop_id, sku, name, status, min_price, max_price, limit = 10 } = args;

  const actualLimit = Math.min(Math.max(1, limit), 20);

  // Check access policy
  const accessConfig = await getAccessPolicyConfig(shop_id);
  const accessError = validateAccess(accessConfig, 'products');
  if (accessError) {
    return accessError;
  }

  const policy = getDataTypePolicy(accessConfig!, 'products');

  try {
    // Handle api_only mode: Direct API call
    if (isApiOnlyMode(policy)) {
      console.log('[MCP WooCommerce] Using direct API access (api_only mode)');

      const filters: any = {};
      if (sku) filters.sku = sku;
      if (status) filters.status = status;

      // Fetch from WooCommerce API directly
      const apiProducts = await fetchProducts(shop_id, 1, actualLimit, filters);

      let products = apiProducts;

      // Apply client-side filters
      if (name) {
        const nameLower = name.toLowerCase();
        products = products.filter((p: any) =>
          (p.name || '').toLowerCase().includes(nameLower)
        );
      }

      if (min_price !== undefined) {
        products = products.filter((p: any) => parseFloat(p.price) >= min_price);
      }

      if (max_price !== undefined) {
        products = products.filter((p: any) => parseFloat(p.price) <= max_price);
      }

      // Limit results
      products = products.slice(0, actualLimit);

      // Format for LLM
      const formattedProducts: LlmProduct[] = products.map((p: any) => ({
        id: p.id.toString(),
        name: p.name,
        sku: p.sku || undefined,
        price: p.price || undefined,
        currency: undefined,
        status: p.status || undefined,
        description: p.description || undefined,
        tags: p.tags?.map((t: any) => t.name) || undefined
      }));

      const cleanedProducts = cleanResponseData(formattedProducts);

      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            count: products.length,
            limit: actualLimit,
            source: 'api_direct',
            access_mode: 'api_only',
            notice: createApiOnlyNotice('products'),
            products: cleanedProducts
          })
        }]
      };
    }

    // Handle sync mode: Use Qdrant or SQL cache
    if (isSyncAllowed(policy)) {
      const qdrantConfig = await getStoreQdrantConfig(shop_id);

      if (qdrantConfig && qdrantConfig.enabled && qdrantConfig.syncProducts) {
        const products = await queryQdrantProducts(
          shop_id,
          qdrantConfig.shopname,
          { sku, name, status, minPrice: min_price, maxPrice: max_price },
          actualLimit
        );

        const cleanedProducts = cleanResponseData(products);

        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              count: products.length,
              limit: actualLimit,
              source: 'qdrant',
              access_mode: 'sync',
              products: cleanedProducts
            })
          }]
        };
      } else {
        let query = supabase
          .from('woocommerce_products_cache')
          .select('*')
          .eq('store_id', shop_id);

        if (sku) query = query.eq('sku', sku);
        if (status) query = query.eq('stock_status', status);

        query = query.limit(actualLimit);

        const { data: cachedProducts, error: cacheError } = await query;

        if (cacheError) {
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({ error: `Failed to fetch products: ${cacheError.message}` })
            }],
            isError: true
          };
        }

        let products = cachedProducts || [];

        if (name) {
          const nameLower = name.toLowerCase();
          products = products.filter((p: any) =>
            (p.name || '').toLowerCase().includes(nameLower)
          );
        }

        if (min_price !== undefined) {
          products = products.filter((p: any) => (parseFloat(p.price) || 0) >= min_price);
        }

        if (max_price !== undefined) {
          products = products.filter((p: any) => (parseFloat(p.price) || 0) <= max_price);
        }

        products = products.slice(0, actualLimit);

        const formattedProducts: LlmProduct[] = products.map((p: any) => ({
          id: p.wc_product_id || p.id,
          name: p.name,
          sku: p.sku || undefined,
          price: p.price || undefined,
          currency: p.currency || undefined,
          status: p.stock_status || p.status || undefined,
          description: p.description || undefined,
          tags: undefined
        }));

        const cleanedProducts = cleanResponseData(formattedProducts);

        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              count: formattedProducts.length,
              limit: actualLimit,
              source: 'sql_cache',
              access_mode: 'sync',
              products: cleanedProducts
            })
          }]
        };
      }
    }

    // Fallback (should not reach here)
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({ error: 'Invalid access policy configuration' })
      }],
      isError: true
    };
  } catch (error) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({ error: `Failed to fetch products: ${error instanceof Error ? error.message : 'Unknown error'}` })
      }],
      isError: true
    };
  }
}

/**
 * Fetch all orders with pagination (for filtering by customer name)
 */
async function fetchAllOrdersPages(
  shop_id: string,
  maxPages: number = 10,
  filters?: WooCommerceOrderFilters
): Promise<WooCommerceOrder[]> {
  const allOrders: WooCommerceOrder[] = [];
  let page = 1;
  let hasMore = true;

  while (hasMore && page <= maxPages) {
    const orders = await fetchOrders(shop_id, page, 100, filters);

    if (orders.length === 0) {
      hasMore = false;
    } else {
      allOrders.push(...orders);
      hasMore = orders.length === 100;
      page++;
    }
  }

  return allOrders;
}

/**
 * Handle woocommerce_get_order tool
 */
async function handleGetOrder(args: Record<string, any>): Promise<ToolCallResult> {
  const { shop_id, order_id } = args;

  // Validate order_id is provided
  if (!order_id) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: 'order_id parameter is required'
        })
      }],
      isError: true
    };
  }

  // Check access policy
  const accessConfig = await getAccessPolicyConfig(shop_id);
  const accessError = validateAccess(accessConfig, 'orders');
  if (accessError) {
    return accessError;
  }

  const policy = getDataTypePolicy(accessConfig!, 'orders');

  try {
    // Always fetch from API (no cache for single order lookups)
    const order = await fetchOrder(shop_id, order_id);

    // Format for LLM
    const formattedOrder = formatOrderForLlm(order);
    const cleanedOrder = cleanResponseData(formattedOrder);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          access_mode: policy,
          notice: isApiOnlyMode(policy) ? createApiOnlyNotice('orders') : undefined,
          order: cleanedOrder
        })
      }]
    };
  } catch (error) {
    console.error('[MCP WooCommerce] Error fetching order:', error);
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: `Failed to fetch order: ${error instanceof Error ? error.message : 'Unknown error'}`
        })
      }],
      isError: true
    };
  }
}

/**
 * Handle woocommerce_list_orders tool
 */
async function handleListOrders(args: Record<string, any>): Promise<ToolCallResult> {
  const {
    shop_id,
    created_after,
    created_before,
    updated_after,
    updated_before,
    customer_email,
    customer_name,
    status,
    limit = 5
  } = args;

  // Validate at least one filter is provided
  const hasFilter = created_after || created_before || updated_after || updated_before || customer_email || customer_name;
  if (!hasFilter) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: 'At least one filter is required: created_after, created_before, updated_after, updated_before, customer_email, or customer_name'
        })
      }],
      isError: true
    };
  }

  // Enforce limit constraints
  const actualLimit = Math.min(Math.max(1, limit), 20);

  // Check access policy
  const accessConfig = await getAccessPolicyConfig(shop_id);
  const accessError = validateAccess(accessConfig, 'orders');
  if (accessError) {
    return accessError;
  }

  const policy = getDataTypePolicy(accessConfig!, 'orders');

  try {
    // Build filters
    const filters: WooCommerceOrderFilters = {};
    if (status) filters.status = status;
    if (created_after) filters.after = created_after;
    if (created_before) filters.before = created_before;
    if (updated_after) filters.modified_after = updated_after;
    if (updated_before) filters.modified_before = updated_before;

    // Handle customer_email: WooCommerce requires customer ID (integer), not email
    if (customer_email) {
      try {
        // First, search for customer by email to get their ID
        // Fetch more customers (up to 10) to handle edge cases
        const customers = await fetchCustomers(shop_id, 1, 10, { email: customer_email });

        console.log(`[MCP WooCommerce] Customer search for email "${customer_email}": found ${customers.length} customers`);

        if (customers.length === 0) {
          // Fallback: Try fetching recent orders and filter by billing email locally
          console.log(`[MCP WooCommerce] No customer found, trying fallback: fetch orders and filter by billing email`);

          const fallbackOrders = await fetchAllOrdersPages(shop_id, 5, filters);
          const emailLower = customer_email.toLowerCase();
          const matchedOrders = fallbackOrders.filter(order =>
            order.billing.email && order.billing.email.toLowerCase() === emailLower
          );

          if (matchedOrders.length === 0) {
            return {
              content: [{
                type: 'text',
                text: JSON.stringify({
                  count: 0,
                  limit: actualLimit,
                  filters_applied: {
                    created_after,
                    created_before,
                    updated_after,
                    updated_before,
                    customer_email,
                    customer_name,
                    status
                  },
                  orders: [],
                  message: `No orders found for email: ${customer_email}`
                })
              }]
            };
          }

          // Use the matched orders
          orders = matchedOrders.slice(0, actualLimit);
          const formattedOrders = orders.map(formatOrderForLlm);

          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                count: formattedOrders.length,
                limit: actualLimit,
                filters_applied: {
                  created_after,
                  created_before,
                  updated_after,
                  updated_before,
                  customer_email,
                  customer_name,
                  status
                },
                orders: formattedOrders,
                note: 'Found via billing email search (customer not found in customer list)'
              })
            }]
          };
        }

        // Use the customer ID for filtering
        filters.customer = customers[0].id.toString();
      } catch (error) {
        console.error('[MCP WooCommerce] Error searching customer by email:', error);
        // Continue without customer filter (will fallback to other filters if available)
      }
    }

    // Fetch orders from WooCommerce API
    let orders: WooCommerceOrder[];

    if (customer_name) {
      // If filtering by customer name, we need to fetch and filter locally
      // because WooCommerce doesn't support name filtering directly
      const allOrders = await fetchAllOrdersPages(shop_id, 5, filters);
      const lowerName = customer_name.toLowerCase();
      orders = allOrders.filter(order => {
        const fullName = `${order.billing.first_name} ${order.billing.last_name}`.toLowerCase();
        return fullName.includes(lowerName);
      });
    } else {
      // Direct API fetch with filters
      orders = await fetchOrders(shop_id, 1, actualLimit, filters);
    }

    // Apply limit
    const limitedOrders = orders.slice(0, actualLimit);

    // Format for LLM
    const formattedOrders = limitedOrders.map(formatOrderForLlm);
    const cleanedOrders = cleanResponseData(formattedOrders);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          count: formattedOrders.length,
          limit: actualLimit,
          source: isApiOnlyMode(policy) ? 'api_direct' : 'api',
          access_mode: policy,
          notice: isApiOnlyMode(policy) ? createApiOnlyNotice('orders') : undefined,
          filters_applied: {
            created_after,
            created_before,
            updated_after,
            updated_before,
            customer_email,
            customer_name,
            status
          },
          orders: cleanedOrders
        })
      }]
    };
  } catch (error) {
    console.error('[MCP WooCommerce] Error fetching orders:', error);
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: `Failed to fetch orders: ${error instanceof Error ? error.message : 'Unknown error'}`
        })
      }],
      isError: true
    };
  }
}

/**
 * Handle woocommerce_get_customer tool (replaces list_customers)
 */
async function handleGetCustomer(args: Record<string, any>): Promise<ToolCallResult> {
  const { shop_id, email } = args;

  // Validate email is provided
  if (!email) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: 'Email parameter is required'
        })
      }],
      isError: true
    };
  }

  // Check access policy
  const accessConfig = await getAccessPolicyConfig(shop_id);
  const accessError = validateAccess(accessConfig, 'customers');
  if (accessError) {
    return accessError;
  }

  const policy = getDataTypePolicy(accessConfig!, 'customers');

  try {
    // Fetch customer by email from WooCommerce API
    const customers = await fetchCustomers(shop_id, 1, 1, { email });

    if (customers.length === 0) {
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            error: `No customer found with email: ${email}`
          })
        }],
        isError: true
      };
    }

    // Return only the first customer
    const customer = formatCustomerForLlm(customers[0]);
    const cleanedCustomer = cleanResponseData(customer);

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          access_mode: policy,
          notice: isApiOnlyMode(policy) ? createApiOnlyNotice('customers') : undefined,
          customer: cleanedCustomer
        })
      }]
    };
  } catch (error) {
    console.error('[MCP WooCommerce] Error fetching customer:', error);
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: `Failed to fetch customer: ${error instanceof Error ? error.message : 'Unknown error'}`
        })
      }],
      isError: true
    };
  }
}

/**
 * Handle custom content search
 */
async function handleSearchCustomContent(args: Record<string, any>): Promise<ToolCallResult> {
  const { shop_id, query, limit = 5 } = args;

  try {
    // Get store config for Qdrant connection
    const qdrantConfig = await getStoreQdrantConfig(shop_id);

    if (!qdrantConfig) {
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            error: 'Store configuration not found'
          })
        }],
        isError: true
      };
    }

    // Query custom content from Qdrant
    const results = await queryQdrantCustomContent(
      shop_id,
      qdrantConfig.shopname,
      query,
      Math.min(limit, 10) // Max 10 results
    );

    if (results.length === 0) {
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            message: 'No custom content found matching your query',
            results: []
          })
        }],
        isError: false
      };
    }

    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          results: results.map(r => ({
            id: r.id,
            title: r.title,
            content_type: r.contentType,
            excerpt: r.excerpt,
            chunk_info: `Chunk ${r.chunkIndex + 1} of ${r.totalChunks}`,
            relevance_score: Math.round(r.relevanceScore * 100) / 100,
            original_filename: r.originalFilename,
            page_count: r.pageCount
          })),
          total: results.length
        })
      }],
      isError: false
    };
  } catch (error: any) {
    console.error('[MCP WooCommerce] Error searching custom content:', error);
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({ error: `Failed to search custom content: ${error instanceof Error ? error.message : 'Unknown error'}` })
      }],
      isError: true
    };
  }
}

/**
 * Handle tool call
 */
async function handleToolCall(params: ToolCallParams): Promise<ToolCallResult> {
  const { name, arguments: args = {} } = params;

  // Validate shop_id is provided
  const validation = validateParams(args, ['shop_id']);
  if (!validation.valid) {
    return {
      content: [{
        type: 'text',
        text: JSON.stringify({
          error: `Missing required parameters: ${validation.missing?.join(', ')}`
        })
      }],
      isError: true
    };
  }

  // Route to appropriate handler
  switch (name) {
    case 'woocommerce_get_products':
      return await handleGetProducts(args);

    case 'woocommerce_get_order':
      const orderValidation = validateParams(args, ['shop_id', 'order_id']);
      if (!orderValidation.valid) {
        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              error: `Missing required parameters: ${orderValidation.missing?.join(', ')}`
            })
          }],
          isError: true
        };
      }
      return await handleGetOrder(args);

    case 'woocommerce_list_orders':
      return await handleListOrders(args);

    case 'woocommerce_get_customer':
      const customerValidation = validateParams(args, ['shop_id', 'email']);
      if (!customerValidation.valid) {
        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              error: `Missing required parameters: ${customerValidation.missing?.join(', ')}`
            })
          }],
          isError: true
        };
      }
      return await handleGetCustomer(args);

    case 'woocommerce_search_custom_content':
      const customContentValidation = validateParams(args, ['shop_id', 'query']);
      if (!customContentValidation.valid) {
        return {
          content: [{
            type: 'text',
            text: JSON.stringify({
              error: `Missing required parameters: ${customContentValidation.missing?.join(', ')}`
            })
          }],
          isError: true
        };
      }
      return await handleSearchCustomContent(args);

    // Legacy tool names for backward compatibility
    case 'woocommerce_list_customers':
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            error: 'This tool has been removed. Use woocommerce_get_customer with email parameter instead.'
          })
        }],
        isError: true
      };

    case 'woocommerce_get_customer_orders':
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({
            error: 'This tool has been removed. Use woocommerce_list_orders with customer_email filter instead.'
          })
        }],
        isError: true
      };

    default:
      return {
        content: [{
          type: 'text',
          text: JSON.stringify({ error: `Unknown tool: ${name}` })
        }],
        isError: true
      };
  }
}

/**
 * Main request handler with MCP SSE protocol
 */
serve(async (req: Request) => {
  // CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Authorization, Content-Type'
      }
    });
  }

  // MCP SSE endpoint - only POST requests
  if (req.method !== 'POST') {
    return new Response(JSON.stringify({ error: 'Method not allowed. Use POST.' }), {
      status: 405,
      headers: { 'Content-Type': 'application/json' }
    });
  }

  // Authenticate with internal API key
  const authResult = await requireInternalApiKey(req, supabase, 'read_orders');

  if (!authResult.valid) {
    return createInternalApiKeyErrorResponse(authResult);
  }

  // Create SSE response
  const { response, controller } = createSseResponse();

  // Parse JSON-RPC request
  let rpcRequest: JsonRpcRequest;
  try {
    rpcRequest = await parseJsonRpcRequest(req);
  } catch (error) {
    sendSseMessage(
      controller,
      createJsonRpcError(
        null,
        JsonRpcErrorCode.PARSE_ERROR,
        error instanceof Error ? error.message : 'Parse error'
      )
    );
    closeSseStream(controller);
    return response;
  }

  const { id, method, params } = rpcRequest;

  try {
    // Handle MCP methods
    switch (method) {
      case 'initialize':
        if (!validateInitializeParams(params)) {
          sendSseMessage(
            controller,
            createJsonRpcError(id!, JsonRpcErrorCode.INVALID_PARAMS, 'Invalid initialize parameters')
          );
          break;
        }

        const initResult = createInitializeResult(SERVER_NAME, SERVER_VERSION);
        sendSseMessage(controller, createJsonRpcSuccess(id!, initResult));
        break;

      case 'tools/list':
        sendSseMessage(controller, createJsonRpcSuccess(id!, { tools: TOOLS }));
        break;

      case 'tools/call':
        if (!validateToolCallParams(params)) {
          sendSseMessage(
            controller,
            createJsonRpcError(id!, JsonRpcErrorCode.INVALID_PARAMS, 'Invalid tool call parameters')
          );
          break;
        }

        const toolResult = await handleToolCall(params);
        sendSseMessage(controller, createJsonRpcSuccess(id!, toolResult));
        break;

      default:
        sendSseMessage(
          controller,
          createJsonRpcError(id!, JsonRpcErrorCode.METHOD_NOT_FOUND, `Method not found: ${method}`)
        );
    }
  } catch (error) {
    console.error('[MCP WooCommerce] Error handling request:', error);
    sendSseMessage(
      controller,
      createJsonRpcError(
        id!,
        JsonRpcErrorCode.INTERNAL_ERROR,
        error instanceof Error ? error.message : 'Internal error'
      )
    );
  }

  // Close stream
  closeSseStream(controller);
  return response;
});
