export function computeDcf(input = {}) {
  const price = Number(input.price_au_usd_oz ?? 0);
  const production = Number(input.payable_production_oz_per_year ?? 0);
  const lifeYears = Math.max(0, Math.floor(Number(input.life_years ?? 0)));
  const opex = Number(input.opex_annual ?? 0);
  const sustaining = Number(input.sustaining_capex ?? 0);
  const royalties = Number(input.royalties ?? 0);
  const taxes = Number(input.taxes ?? 0);
  const closure = Number(input.closure_provision ?? 0);
  const discountRate = Number(input.discount_rate ?? 0.08);

  if (!price || !production || !lifeYears) {
    return { valuation_tier: 't2_dcf', status: 'insufficient_inputs', npv_usd: null, annual_cash_flows: [] };
  }

  const annual = [];
  let npv = 0;
  for (let year = 1; year <= lifeYears; year++) {
    const revenue = production * price;
    const closureCost = year === lifeYears ? closure : 0;
    const freeCashFlow = revenue - opex - sustaining - royalties - taxes - closureCost;
    const discountFactor = 1 / ((1 + discountRate) ** year);
    const discounted = freeCashFlow * discountFactor;
    npv += discounted;
    annual.push({ year, revenue_usd: revenue, free_cash_flow_usd: freeCashFlow, discounted_fcf_usd: discounted });
  }
  return {
    valuation_tier: 't2_dcf',
    status: 'ok',
    npv_usd: Math.round(npv * 100) / 100,
    discount_rate: discountRate,
    annual_cash_flows: annual.map(r => ({
      year: r.year,
      revenue_usd: Math.round(r.revenue_usd * 100) / 100,
      free_cash_flow_usd: Math.round(r.free_cash_flow_usd * 100) / 100,
      discounted_fcf_usd: Math.round(r.discounted_fcf_usd * 100) / 100,
    })),
  };
}
