/**
 * BigCommerce Analytics Tools
 * Note: BigCommerce doesn't have a dedicated analytics API endpoint,
 * so these tools aggregate data from orders and products
 */

import { BigCommerceClient } from '../clients/bigcommerce.js';

export function registerAnalyticsTools(client: BigCommerceClient) {
  return [
    {
      name: 'bigcommerce_get_store_analytics',
      description: 'Get store-wide analytics including orders, revenue, and customer metrics',
      inputSchema: {
        type: 'object',
        properties: {
          start_date: { 
            type: 'string', 
            description: 'Start date for analytics period (RFC 2822 or ISO 8601)' 
          },
          end_date: { 
            type: 'string', 
            description: 'End date for analytics period (RFC 2822 or ISO 8601)' 
          },
        },
      },
      handler: async (args: any) => {
        // Fetch orders for the period
        const params = new URLSearchParams();
        if (args.start_date) params.append('min_date_created', args.start_date);
        if (args.end_date) params.append('max_date_created', args.end_date);
        const response = await client.get<any>(`/orders?${params.toString()}`, 'v2');
        const orders = response || [];

        // Calculate analytics
        const orderArray = Array.isArray(orders) ? orders : [];
        const totalOrders = orderArray.length;
        const totalRevenue = orderArray.reduce((sum: number, order: any) => 
          sum + (order.total_inc_tax || 0), 0
        );
        const averageOrderValue = totalOrders > 0 ? totalRevenue / totalOrders : 0;

        // Get unique customers
        const uniqueCustomers = new Set(orderArray.map((order: any) => order.customer_id));
        
        const analytics = {
          period: {
            start_date: args.start_date,
            end_date: args.end_date,
          },
          total_orders: totalOrders,
          total_revenue: Math.round(totalRevenue * 100) / 100,
          average_order_value: Math.round(averageOrderValue * 100) / 100,
          total_customers: uniqueCustomers.size,
        };

        return { content: [{ type: 'text', text: JSON.stringify(analytics, null, 2) }] };
      },
    },
    {
      name: 'bigcommerce_get_product_analytics',
      description: 'Get analytics for a specific product',
      inputSchema: {
        type: 'object',
        properties: {
          product_id: { type: 'number', description: 'Product ID' },
          start_date: { 
            type: 'string', 
            description: 'Start date for analytics period (RFC 2822 or ISO 8601)' 
          },
          end_date: { 
            type: 'string', 
            description: 'End date for analytics period (RFC 2822 or ISO 8601)' 
          },
        },
        required: ['product_id'],
      },
      handler: async (args: any) => {
        // Get product details
        const product = await client.get<any>(`/catalog/products/${args.product_id}`);

        // Fetch orders for the period
        const params = new URLSearchParams();
        if (args.start_date) params.append('min_date_created', args.start_date);
        if (args.end_date) params.append('max_date_created', args.end_date);
        const ordersResponse = await client.get<any>(`/orders?${params.toString()}`, 'v2');
        const orders = ordersResponse || [];

        const orderArray = Array.isArray(orders) ? orders : [];
        
        // Analyze orders for this product
        let totalQuantitySold = 0;
        let totalRevenue = 0;
        let orderCount = 0;

        for (const order of orderArray) {
          try {
            const orderProducts = await client.get<any>(`/orders/${order.id}/products`, 'v2');
            const orderProductArray = Array.isArray(orderProducts) ? orderProducts : [];
            
            for (const item of orderProductArray) {
              if (item.product_id === args.product_id) {
                totalQuantitySold += item.quantity || 0;
                totalRevenue += item.total_inc_tax || 0;
                orderCount++;
              }
            }
          } catch (error) {
            // Continue if order products can't be fetched
            continue;
          }
        }

        const analytics = {
          product_id: args.product_id,
          product_name: product.data?.name,
          period: {
            start_date: args.start_date,
            end_date: args.end_date,
          },
          orders: orderCount,
          quantity_sold: totalQuantitySold,
          revenue: Math.round(totalRevenue * 100) / 100,
          current_inventory: product.data?.inventory_level,
        };

        return { content: [{ type: 'text', text: JSON.stringify(analytics, null, 2) }] };
      },
    },
  ];
}
