import type { BigCommerceClient } from '../clients/bigcommerce.js';
import type { Product, ProductVariant, ProductImage, CustomField, BulkPricingRule } from '../types/index.js';

export function registerProductTools(client: BigCommerceClient) {
  return {
    // Product CRUD Operations
    bigcommerce_list_products: {
      description: 'List all products with optional filters (name, SKU, price range, categories, brand, availability)',
      parameters: {
        type: 'object' as const,
        properties: {
          name: { type: 'string', description: 'Filter by product name (partial match)' },
          sku: { type: 'string', description: 'Filter by SKU' },
          price_min: { type: 'number', description: 'Minimum price' },
          price_max: { type: 'number', description: 'Maximum price' },
          categories: { type: 'string', description: 'Comma-separated category IDs' },
          brand_id: { type: 'number', description: 'Filter by brand ID' },
          is_visible: { type: 'boolean', description: 'Filter by visibility' },
          is_featured: { type: 'boolean', description: 'Filter by featured status' },
          inventory_level: { type: 'number', description: 'Filter by minimum inventory level' },
          page: { type: 'number', description: 'Page number (default: 1)' },
          limit: { type: 'number', description: 'Items per page (default: 50, max: 250)' },
        },
      },
      handler: async (params: Record<string, unknown>) => {
        const queryParams: Record<string, string | number> = {};
        if (params.name) queryParams['name:like'] = params.name as string;
        if (params.sku) queryParams.sku = params.sku as string;
        if (params.price_min) queryParams['price:min'] = params.price_min as number;
        if (params.price_max) queryParams['price:max'] = params.price_max as number;
        if (params.categories) queryParams.categories = params.categories as string;
        if (params.brand_id) queryParams.brand_id = params.brand_id as number;
        if (params.is_visible !== undefined) queryParams.is_visible = params.is_visible ? 'true' : 'false';
        if (params.is_featured !== undefined) queryParams.is_featured = params.is_featured ? 'true' : 'false';
        if (params.inventory_level) queryParams['inventory_level:min'] = params.inventory_level as number;

        const page = (params.page as number) || 1;
        const limit = (params.limit as number) || 50;

        const result = await client.getPage<Product>('/catalog/products', page, limit, queryParams);
        return { products: result.data, meta: result.meta };
      },
    },

    bigcommerce_get_product: {
      description: 'Get a single product by ID with full details (variants, images, custom fields)',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          include_variants: { type: 'boolean', description: 'Include product variants (default: true)' },
          include_images: { type: 'boolean', description: 'Include product images (default: true)' },
          include_custom_fields: { type: 'boolean', description: 'Include custom fields (default: true)' },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number; include_variants?: boolean; include_images?: boolean; include_custom_fields?: boolean }) => {
        const queryParams: string[] = [];
        if (params.include_variants !== false) queryParams.push('include=variants');
        if (params.include_images !== false) queryParams.push('include=images');
        if (params.include_custom_fields !== false) queryParams.push('include=custom_fields');
        
        const query = queryParams.length > 0 ? `?${queryParams.join('&')}` : '';
        const result = await client.get<{ data: Product }>(`/catalog/products/${params.product_id}${query}`);
        return result.data;
      },
    },

    bigcommerce_create_product: {
      description: 'Create a new product with full details',
      parameters: {
        type: 'object' as const,
        properties: {
          name: { type: 'string', description: 'Product name', required: true },
          type: { type: 'string', enum: ['physical', 'digital'], description: 'Product type', required: true },
          sku: { type: 'string', description: 'SKU' },
          description: { type: 'string', description: 'Product description' },
          weight: { type: 'number', description: 'Weight in pounds/ounces', required: true },
          price: { type: 'number', description: 'Price', required: true },
          cost_price: { type: 'number', description: 'Cost price' },
          retail_price: { type: 'number', description: 'Retail price (MSRP)' },
          sale_price: { type: 'number', description: 'Sale price' },
          categories: { type: 'array', items: { type: 'number' }, description: 'Category IDs' },
          brand_id: { type: 'number', description: 'Brand ID' },
          inventory_level: { type: 'number', description: 'Initial inventory level' },
          inventory_tracking: { type: 'string', enum: ['none', 'product', 'variant'], description: 'Inventory tracking type' },
          is_visible: { type: 'boolean', description: 'Product visibility' },
          is_featured: { type: 'boolean', description: 'Featured product' },
          condition: { type: 'string', enum: ['New', 'Used', 'Refurbished'], description: 'Product condition' },
        },
        required: ['name', 'type', 'weight', 'price'],
      },
      handler: async (params: Partial<Product>) => {
        const result = await client.post<{ data: Product }>('/catalog/products', params);
        return result.data;
      },
    },

    bigcommerce_update_product: {
      description: 'Update an existing product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          name: { type: 'string', description: 'Product name' },
          sku: { type: 'string', description: 'SKU' },
          description: { type: 'string', description: 'Product description' },
          price: { type: 'number', description: 'Price' },
          cost_price: { type: 'number', description: 'Cost price' },
          sale_price: { type: 'number', description: 'Sale price' },
          inventory_level: { type: 'number', description: 'Inventory level' },
          is_visible: { type: 'boolean', description: 'Product visibility' },
          is_featured: { type: 'boolean', description: 'Featured product' },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number; [key: string]: unknown }) => {
        const { product_id, ...updateData } = params;
        const result = await client.put<{ data: Product }>(`/catalog/products/${product_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_product: {
      description: 'Delete a product by ID',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number }) => {
        await client.delete(`/catalog/products/${params.product_id}`);
        return { success: true, message: `Product ${params.product_id} deleted` };
      },
    },

    // Product Variants
    bigcommerce_list_product_variants: {
      description: 'List all variants for a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number }) => {
        const result = await client.get<{ data: ProductVariant[] }>(`/catalog/products/${params.product_id}/variants`);
        return result.data;
      },
    },

    bigcommerce_get_product_variant: {
      description: 'Get a specific variant by ID',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          variant_id: { type: 'number', description: 'Variant ID', required: true },
        },
        required: ['product_id', 'variant_id'],
      },
      handler: async (params: { product_id: number; variant_id: number }) => {
        const result = await client.get<{ data: ProductVariant }>(`/catalog/products/${params.product_id}/variants/${params.variant_id}`);
        return result.data;
      },
    },

    bigcommerce_create_product_variant: {
      description: 'Create a new product variant',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          sku: { type: 'string', description: 'Variant SKU' },
          price: { type: 'number', description: 'Variant price' },
          cost_price: { type: 'number', description: 'Variant cost price' },
          weight: { type: 'number', description: 'Variant weight' },
          inventory_level: { type: 'number', description: 'Inventory level' },
          option_values: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                option_id: { type: 'number' },
                label: { type: 'string' },
              },
            },
            description: 'Array of option values',
            required: true,
          },
        },
        required: ['product_id', 'option_values'],
      },
      handler: async (params: { product_id: number; [key: string]: unknown }) => {
        const { product_id, ...variantData } = params;
        const result = await client.post<{ data: ProductVariant }>(`/catalog/products/${product_id}/variants`, variantData);
        return result.data;
      },
    },

    bigcommerce_update_product_variant: {
      description: 'Update a product variant',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          variant_id: { type: 'number', description: 'Variant ID', required: true },
          sku: { type: 'string', description: 'Variant SKU' },
          price: { type: 'number', description: 'Variant price' },
          inventory_level: { type: 'number', description: 'Inventory level' },
        },
        required: ['product_id', 'variant_id'],
      },
      handler: async (params: { product_id: number; variant_id: number; [key: string]: unknown }) => {
        const { product_id, variant_id, ...updateData } = params;
        const result = await client.put<{ data: ProductVariant }>(`/catalog/products/${product_id}/variants/${variant_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_product_variant: {
      description: 'Delete a product variant',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          variant_id: { type: 'number', description: 'Variant ID', required: true },
        },
        required: ['product_id', 'variant_id'],
      },
      handler: async (params: { product_id: number; variant_id: number }) => {
        await client.delete(`/catalog/products/${params.product_id}/variants/${params.variant_id}`);
        return { success: true, message: `Variant ${params.variant_id} deleted` };
      },
    },

    // Product Images
    bigcommerce_list_product_images: {
      description: 'List all images for a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number }) => {
        const result = await client.get<{ data: ProductImage[] }>(`/catalog/products/${params.product_id}/images`);
        return result.data;
      },
    },

    bigcommerce_create_product_image: {
      description: 'Add an image to a product (provide image_url or image_file)',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          image_url: { type: 'string', description: 'Public URL of the image' },
          is_thumbnail: { type: 'boolean', description: 'Set as thumbnail' },
          sort_order: { type: 'number', description: 'Sort order' },
          description: { type: 'string', description: 'Image alt text/description' },
        },
        required: ['product_id', 'image_url'],
      },
      handler: async (params: { product_id: number; [key: string]: unknown }) => {
        const { product_id, ...imageData } = params;
        const result = await client.post<{ data: ProductImage }>(`/catalog/products/${product_id}/images`, imageData);
        return result.data;
      },
    },

    bigcommerce_update_product_image: {
      description: 'Update a product image',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          image_id: { type: 'number', description: 'Image ID', required: true },
          is_thumbnail: { type: 'boolean', description: 'Set as thumbnail' },
          sort_order: { type: 'number', description: 'Sort order' },
          description: { type: 'string', description: 'Image alt text/description' },
        },
        required: ['product_id', 'image_id'],
      },
      handler: async (params: { product_id: number; image_id: number; [key: string]: unknown }) => {
        const { product_id, image_id, ...updateData } = params;
        const result = await client.put<{ data: ProductImage }>(`/catalog/products/${product_id}/images/${image_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_product_image: {
      description: 'Delete a product image',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          image_id: { type: 'number', description: 'Image ID', required: true },
        },
        required: ['product_id', 'image_id'],
      },
      handler: async (params: { product_id: number; image_id: number }) => {
        await client.delete(`/catalog/products/${params.product_id}/images/${params.image_id}`);
        return { success: true, message: `Image ${params.image_id} deleted` };
      },
    },

    // Custom Fields
    bigcommerce_list_product_custom_fields: {
      description: 'List custom fields for a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number }) => {
        const result = await client.get<{ data: CustomField[] }>(`/catalog/products/${params.product_id}/custom-fields`);
        return result.data;
      },
    },

    bigcommerce_create_product_custom_field: {
      description: 'Add a custom field to a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          name: { type: 'string', description: 'Field name', required: true },
          value: { type: 'string', description: 'Field value', required: true },
        },
        required: ['product_id', 'name', 'value'],
      },
      handler: async (params: { product_id: number; name: string; value: string }) => {
        const { product_id, ...fieldData } = params;
        const result = await client.post<{ data: CustomField }>(`/catalog/products/${product_id}/custom-fields`, fieldData);
        return result.data;
      },
    },

    bigcommerce_update_product_custom_field: {
      description: 'Update a product custom field',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          custom_field_id: { type: 'number', description: 'Custom field ID', required: true },
          name: { type: 'string', description: 'Field name' },
          value: { type: 'string', description: 'Field value' },
        },
        required: ['product_id', 'custom_field_id'],
      },
      handler: async (params: { product_id: number; custom_field_id: number; [key: string]: unknown }) => {
        const { product_id, custom_field_id, ...updateData } = params;
        const result = await client.put<{ data: CustomField }>(`/catalog/products/${product_id}/custom-fields/${custom_field_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_product_custom_field: {
      description: 'Delete a product custom field',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          custom_field_id: { type: 'number', description: 'Custom field ID', required: true },
        },
        required: ['product_id', 'custom_field_id'],
      },
      handler: async (params: { product_id: number; custom_field_id: number }) => {
        await client.delete(`/catalog/products/${params.product_id}/custom-fields/${params.custom_field_id}`);
        return { success: true, message: `Custom field ${params.custom_field_id} deleted` };
      },
    },

    // Bulk Pricing Rules
    bigcommerce_list_product_bulk_pricing: {
      description: 'List bulk pricing rules for a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
        },
        required: ['product_id'],
      },
      handler: async (params: { product_id: number }) => {
        const result = await client.get<{ data: BulkPricingRule[] }>(`/catalog/products/${params.product_id}/bulk-pricing-rules`);
        return result.data;
      },
    },

    bigcommerce_create_product_bulk_pricing: {
      description: 'Create a bulk pricing rule for a product',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          quantity_min: { type: 'number', description: 'Minimum quantity', required: true },
          quantity_max: { type: 'number', description: 'Maximum quantity', required: true },
          type: { type: 'string', enum: ['price', 'percent', 'fixed'], description: 'Discount type', required: true },
          amount: { type: 'number', description: 'Discount amount', required: true },
        },
        required: ['product_id', 'quantity_min', 'quantity_max', 'type', 'amount'],
      },
      handler: async (params: { product_id: number; [key: string]: unknown }) => {
        const { product_id, ...ruleData } = params;
        const result = await client.post<{ data: BulkPricingRule }>(`/catalog/products/${product_id}/bulk-pricing-rules`, ruleData);
        return result.data;
      },
    },

    bigcommerce_update_product_bulk_pricing: {
      description: 'Update a bulk pricing rule',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          bulk_pricing_id: { type: 'number', description: 'Bulk pricing rule ID', required: true },
          quantity_min: { type: 'number', description: 'Minimum quantity' },
          quantity_max: { type: 'number', description: 'Maximum quantity' },
          type: { type: 'string', enum: ['price', 'percent', 'fixed'], description: 'Discount type' },
          amount: { type: 'number', description: 'Discount amount' },
        },
        required: ['product_id', 'bulk_pricing_id'],
      },
      handler: async (params: { product_id: number; bulk_pricing_id: number; [key: string]: unknown }) => {
        const { product_id, bulk_pricing_id, ...updateData } = params;
        const result = await client.put<{ data: BulkPricingRule }>(`/catalog/products/${product_id}/bulk-pricing-rules/${bulk_pricing_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_product_bulk_pricing: {
      description: 'Delete a bulk pricing rule',
      parameters: {
        type: 'object' as const,
        properties: {
          product_id: { type: 'number', description: 'Product ID', required: true },
          bulk_pricing_id: { type: 'number', description: 'Bulk pricing rule ID', required: true },
        },
        required: ['product_id', 'bulk_pricing_id'],
      },
      handler: async (params: { product_id: number; bulk_pricing_id: number }) => {
        await client.delete(`/catalog/products/${params.product_id}/bulk-pricing-rules/${params.bulk_pricing_id}`);
        return { success: true, message: `Bulk pricing rule ${params.bulk_pricing_id} deleted` };
      },
    },
  };
}
