/**
 * Cascade engine.
 *
 * Input: an injury / lineup / weather delta + the set of props it touches.
 * Output: a cascade alert with before/after grade per affected prop.
 *
 * The actual regrade happens in the grading engine; we just compose the
 * notification payload. Persist to `cascade_alerts` and surface in the
 * dead-hours feed + notification bell.
 */

function buildAlert({ trigger, before = [], after = [] } = {}) {
  if (!trigger || typeof trigger !== 'object') {
    throw new Error('cascade: trigger required');
  }
  const beforeByKey = new Map((before || []).map((p) => [p.key, p]));
  const affected = [];
  for (const a of after || []) {
    const b = beforeByKey.get(a.key);
    if (!b) continue;
    if (a.grade === b.grade) continue;
    affected.push({
      key: a.key,
      player: a.player ?? b.player,
      stat: a.stat ?? b.stat,
      old_grade: b.grade,
      new_grade: a.grade,
      old_projection: b.projection ?? null,
      new_projection: a.projection ?? null,
      direction: a.direction ?? b.direction,
    });
  }
  return {
    trigger_type: trigger.type,    // 'injury' | 'lineup' | 'weather' | 'ref' | 'umpire'
    trigger_detail: trigger.detail || trigger,
    affected_props: affected,
    affected_count: affected.length,
    created_at: new Date().toISOString(),
  };
}

module.exports = { buildAlert };
