import type { Product, ProductUnit } from '@/types';

/** Resolve sale unit from product (null = base unit) */
export function findProductUnit(product: Product, unitId?: number | null): ProductUnit | null {
  if (!unitId || !product.units?.length) return null;
  return product.units.find((u) => u.id === unitId) ?? null;
}

/** Default sale unit if product has is_default_sale */
export function getDefaultSaleUnit(product: Product): ProductUnit | null {
  if (!product.units?.length) return null;
  return product.units.find((u) => u.is_default_sale) ?? null;
}

export function unitMultiplier(unit: ProductUnit | null | undefined): number {
  if (!unit) return 1;
  const m = Number(unit.multiplier);
  return m > 0 ? m : 1;
}

/** Sale qty → base stock qty */
export function toBaseQty(saleQty: number, unit?: ProductUnit | null): number {
  return saleQty * unitMultiplier(unit);
}

export function unitLabel(product: Product, unit?: ProductUnit | null): string {
  if (unit) return unit.abbreviation || unit.name;
  return product.unit || 'pcs';
}

export function cartLineKey(productId: number, unitId?: number | null): string {
  return `${productId}:${unitId ?? 0}`;
}

/** Min order / step rules are always in base units */
export function isBaseQtyAllowed(product: Product, baseQty: number): boolean {
  const min = Number(product.min_order_qty) > 0 ? Number(product.min_order_qty) : 1;
  const step = Number(product.order_step) > 0 ? Number(product.order_step) : 1;

  if (baseQty + 0.0001 < min) return false;
  if (step <= 0) return true;

  const diff = baseQty - min;
  const mod = ((diff % step) + step) % step;
  return mod < 0.0001 || Math.abs(mod - step) < 0.0001;
}

/** Suggest next valid sale qty when increasing by delta (usually ±1 sale unit) */
export function nextSaleQty(
  product: Product,
  currentSaleQty: number,
  delta: number,
  unit?: ProductUnit | null
): number | null {
  const mult = unitMultiplier(unit);
  const min = Number(product.min_order_qty) > 0 ? Number(product.min_order_qty) : 1;
  const step = Number(product.order_step) > 0 ? Number(product.order_step) : 1;

  // Walk in sale-unit steps, validate base
  let sale = currentSaleQty + delta;
  if (sale <= 0) return 0;

  // Cap attempts to avoid infinite loop
  for (let i = 0; i < 200; i++) {
    const base = sale * mult;
    if (isBaseQtyAllowed(product, base)) {
      return sale;
    }
    sale += delta > 0 ? 1 : -1;
    if (sale <= 0) return 0;
  }

  // Fallback: jump to min in sale units
  const minSale = Math.max(1, Math.ceil(min / mult));
  if (isBaseQtyAllowed(product, minSale * mult)) return minSale;
  return null;
}

/** Initial sale qty when first adding product */
export function initialSaleQty(product: Product, unit?: ProductUnit | null): number {
  const mult = unitMultiplier(unit);
  const min = Number(product.min_order_qty) > 0 ? Number(product.min_order_qty) : 1;
  // Prefer 1 sale unit if that meets min; else ceil(min/mult)
  const candidate = Math.max(1, Math.ceil(min / mult));
  if (isBaseQtyAllowed(product, candidate * mult)) return candidate;
  // Scan up
  for (let s = 1; s <= 100; s++) {
    if (isBaseQtyAllowed(product, s * mult)) return s;
  }
  return 1;
}

export function qtyRuleMessage(product: Product): string {
  const min = Number(product.min_order_qty) > 0 ? Number(product.min_order_qty) : 1;
  const step = Number(product.order_step) > 0 ? Number(product.order_step) : 1;
  const u = product.unit || 'pcs';
  if (min <= 1 && step <= 1) return '';
  return `Min ${min} ${u}, kelipatan ${step}`;
}
