/**
 * Apply slippage and spread costs
 * @param {number} price - The raw price (e.g. open/close)
 * @param {string} side - 'buy' or 'sell'
 * @param {Array} candles - Full candles array
 * @param {number} idx - Index of the candle to compute ADV from
 * @param {number} orderDollar - Estimated order size (default $5000)
 */
export function applyCosts(price, side, candles, idx, orderDollar = 5000) {
  // Compute ADV from the 10 days prior to idx, or default to 1M if not enough data
  let advDollar = 1000000;
  if (idx >= 10) {
    let volSum = 0;
    for (let i = idx - 10; i < idx; i++) {
      volSum += (candles[i].volume || 0) * (candles[i].close || 0);
    }
    if (volSum > 0) advDollar = volSum / 10;
  }

  // tightest spread ~ 0.02%, scaling up for less liquid
  const spreadPct = Math.max(0.0002, 0.01 / Math.sqrt(advDollar));
  // size-aware slippage
  const slippagePct = 0.0005 * Math.sqrt(orderDollar / advDollar); 
  const drag = (spreadPct / 2) + slippagePct;
  return side === 'buy' ? price * (1 + drag) : price * (1 - drag);
}
