import { WCProduct } from './woocommerce';

export interface ShippingRates {
  shippingCost: number;
  isFreeShipping: boolean;
  shippingClassLabel: string;
}

/**
 * WooCommerce Store Shipping Rate Calculator
 * Configured as per WooCommerce DB shipping zone & shipping class settings:
 * 
 * 1) "economy" (Heavy Shipments):
 *    - Pakistan: Rs. 250
 *    - Rest of World: Rs. 4,000
 * 
 * 2) "overnight" (Small Shipments):
 *    - Pakistan: Rs. 300
 *    - Rest of World: Rs. 5,000
 * 
 * 3) "no-shipping-charges" (Specific / Free Items):
 *    - Pakistan: Rs. 0 (FREE)
 *    - Rest of World: Rs. 0 (FREE)
 * 
 * 4) Unclassed / Default Products:
 *    - Pakistan: Rs. 0 (FREE)
 *    - Rest of World: Rs. 4,000
 */

export function getProductCustomShippingCost(product: WCProduct): number | null {
  if (product.shipping_cost !== undefined && product.shipping_cost !== null && product.shipping_cost !== '') {
    const num = Number(product.shipping_cost);
    if (!isNaN(num) && num >= 0) return num;
  }

  if (product.meta_data && Array.isArray(product.meta_data)) {
    const keysToMatch = ['shipping_cost', '_shipping_cost', 'delivery_charges', 'shipping_fee', 'flat_shipping_rate', '_shipping_fee', 'shipping_charge'];
    const meta = product.meta_data.find((m) => m && keysToMatch.includes((m.key || '').toLowerCase().trim()));
    if (meta && meta.value !== undefined && meta.value !== null && meta.value !== '') {
      const num = Number(meta.value);
      if (!isNaN(num) && num >= 0) return num;
    }
  }

  return null;
}

export function getProductShippingClass(product: WCProduct): string {
  if (product.shipping_class && typeof product.shipping_class === 'string') {
    return product.shipping_class.toLowerCase().trim();
  }

  // Smart taxonomy fallback matching product features/categories
  const name = (product.name || '').toLowerCase();

  if (
    name.includes('shilajit') ||
    name.includes('moringa') ||
    name.includes('capsule') ||
    name.includes('oil') ||
    name.includes('serum')
  ) {
    return 'overnight';
  }

  if (
    name.includes('kit') ||
    name.includes('grooming') ||
    name.includes('machine') ||
    name.includes('trimmer') ||
    name.includes('blender') ||
    name.includes('heavy')
  ) {
    return 'economy';
  }

  if (name.includes('free') || name.includes('sample')) {
    return 'no-shipping-charges';
  }

  return '';
}

export function calculateCartShipping(
  cartItems: Array<{ product: WCProduct; quantity: number }>,
  country: string = 'Pakistan'
): ShippingRates {
  if (!cartItems || cartItems.length === 0) {
    return {
      shippingCost: 0,
      isFreeShipping: true,
      shippingClassLabel: 'Free Delivery',
    };
  }

  const isPakistan = !country || country.toLowerCase() === 'pakistan' || country.toLowerCase() === 'pk';

  let highestRate = 0;
  let highestLabel = 'Standard Shipping';

  cartItems.forEach(({ product }) => {
    const customCost = getProductCustomShippingCost(product);
    if (customCost !== null) {
      if (customCost > highestRate) {
        highestRate = customCost;
        highestLabel = customCost === 0 ? 'Free Shipping' : `Product Flat Delivery (Rs. ${customCost.toLocaleString('en-PK')})`;
      }
      return;
    }

    const sClass = getProductShippingClass(product);

    if (sClass === 'no-shipping-charges' || sClass === 'free') {
      if (highestRate === 0) {
        highestLabel = 'Free Shipping';
      }
    } else if (sClass === 'economy' || sClass.includes('heavy')) {
      const rate = isPakistan ? 250 : 4000;
      if (rate > highestRate) {
        highestRate = rate;
        highestLabel = isPakistan ? 'Economy Delivery (Rs. 250)' : 'International Heavy (Rs. 4,000)';
      }
    } else if (sClass === 'overnight' || sClass.includes('small') || sClass.includes('express')) {
      const rate = isPakistan ? 300 : 5000;
      if (rate > highestRate) {
        highestRate = rate;
        highestLabel = isPakistan ? 'Overnight / Small Delivery (Rs. 300)' : 'International Express (Rs. 5,000)';
      }
    } else {
      // Unclassed product
      const rate = isPakistan ? 0 : 4000;
      if (rate > highestRate) {
        highestRate = rate;
        highestLabel = isPakistan ? 'Free Delivery' : 'International Standard (Rs. 4,000)';
      }
    }
  });

  const isFree = highestRate === 0;

  return {
    shippingCost: highestRate,
    isFreeShipping: isFree,
    shippingClassLabel: isFree ? 'FREE' : highestLabel,
  };
}
