// Decides which products and pack sizes customers can buy through WhatsApp.
//
// Pack sizes the business sells on WhatsApp for specific products. WooCommerce still lists the
// other sizes (and re-syncs them), so the restriction lives here rather than in the database.
// Products without a rule keep all their pack sizes.
const ALLOWED_PACK_SIZES: Array<{ product: RegExp; packs: string[] }> = [
  { product: /(?:^|\b)SC\s*727\b/i, packs: ['5kg', '2kg'] },
];

type VariantLike = {
  name?: string | null;
  attributesJson?: string | null;
  enabled?: boolean;
};
type ProductLike = {
  name: string;
  description?: string | null;
  variants?: VariantLike[];
};

const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');

function ruleFor(productName: string) {
  return ALLOWED_PACK_SIZES.find((r) => r.product.test(productName));
}

/** "SC 727 - 10kg" → "10kg"; reads the Weight attribute first, then the name suffix. */
export function packSizeOf(variant: VariantLike): string | null {
  if (variant.attributesJson) {
    try {
      const attrs = JSON.parse(variant.attributesJson);
      if (Array.isArray(attrs)) {
        const weight = attrs.find(
          (a: any) =>
            a.name?.toLowerCase() === 'weight' ||
            a.slug?.toLowerCase() === 'weight',
        );
        if (weight?.option) return String(weight.option).trim();
      }
    } catch {
      /* fall through to the name */
    }
  }
  const match = (variant.name || '').match(/-\s*([^-]+)$/);
  const suffix = match ? match[1].trim() : '';
  return /\d/.test(suffix) ? suffix : null;
}

/** True when the product is limited to certain pack sizes on WhatsApp (e.g. SC 727). */
export function hasPackSizeRule(productName: string): boolean {
  return !!ruleFor(productName);
}

export function isPackSizeAllowed(
  productName: string,
  packSize: string | null,
): boolean {
  const rule = ruleFor(productName);
  if (!rule || !packSize) return true;
  return rule.packs.some((p) => norm(p) === norm(packSize));
}

/**
 * Lay-by (pay-in-instalments) listings. The store lists each variety twice — a regular product
 * and a "Layby" one with its own prices — and the WhatsApp checkout only takes full payment.
 * Synced descriptions end with "Categories: Layby, Field Crops".
 */
export function isLaybyProduct(product: {
  description?: string | null;
}): boolean {
  const categories =
    (product.description || '').match(/Categories:\s*(.+)$/im)?.[1] || '';
  return /\blay-?by\b/i.test(categories);
}

/** A variant customers may buy on WhatsApp: enabled in the store and in an allowed pack size. */
export function isVariantSellable(
  productName: string,
  variant: VariantLike,
): boolean {
  return (
    variant.enabled !== false &&
    isPackSizeAllowed(productName, packSizeOf(variant))
  );
}

/**
 * Drops variants customers can't buy, and returns null when the product itself is a
 * disallowed pack (e.g. a standalone "SC 727 - 25kg") or has no sellable variants left
 * (e.g. a WooCommerce variable product whose variations are all disabled).
 */
export function filterForChatbot<T extends ProductLike>(
  product: T | null,
): T | null {
  if (!product) return product;
  if (isLaybyProduct(product)) return null;
  if (!isPackSizeAllowed(product.name, packSizeOf({ name: product.name })))
    return null;
  if (!product.variants?.length) return product;
  const variants = product.variants.filter((v) =>
    isVariantSellable(product.name, v),
  );
  if (variants.length === product.variants.length) return product;
  return variants.length ? { ...product, variants } : null;
}

export function filterAllForChatbot<T extends ProductLike>(products: T[]): T[] {
  return products
    .map((p) => filterForChatbot(p))
    .filter((p): p is T => p !== null);
}
