function startOfQuarterUtc(year, quarterStartMonth) {
  return new Date(Date.UTC(year, quarterStartMonth, 1, 0, 0, 0, 0));
}
function getQuarterWindow(now) {
  const year = now.getUTCFullYear();
  const quarterIndex = Math.floor(now.getUTCMonth() / 3);
  const startMonth = quarterIndex * 3;
  const start = startOfQuarterUtc(year, startMonth);
  const end = startOfQuarterUtc(year, startMonth + 3);
  return { start, end };
}
function getPreviousQuarterWindow(now) {
  const current = getQuarterWindow(now);
  const start = startOfQuarterUtc(current.start.getUTCFullYear(), current.start.getUTCMonth() - 3);
  return { start, end: current.start };
}
function monthLabel(year, monthIndex) {
  const month = monthIndex + 1;
  return `${year}-${month < 10 ? `0${month}` : month}`;
}
function getTrailingMonths(now, count) {
  const buckets = [];
  const baseYear = now.getUTCFullYear();
  const baseMonth = now.getUTCMonth();
  for (let offset = count - 1; offset >= 0; offset -= 1) {
    const start = new Date(Date.UTC(baseYear, baseMonth - offset, 1, 0, 0, 0, 0));
    buckets.push({ start, label: monthLabel(start.getUTCFullYear(), start.getUTCMonth()) });
  }
  return buckets;
}
function computeDelta(current, previous) {
  if (previous === 0) {
    return { value: 0, direction: "unchanged" };
  }
  const change = (current - previous) / Math.abs(previous) * 100;
  const value = Math.round(change);
  if (value > 0) return { value, direction: "up" };
  if (value < 0) return { value, direction: "down" };
  return { value: 0, direction: "unchanged" };
}
function extractRate(result) {
  if (!result || result.rates.length === 0) return null;
  const rate = Number(result.rates[0].rate);
  if (!Number.isFinite(rate) || rate <= 0) return null;
  return rate;
}
function convertSumsToBase(perCurrency, baseCode, rates) {
  if (!baseCode) {
    const missing = Array.from(
      new Set(perCurrency.map((entry) => entry.currency).filter((code) => Boolean(code)))
    );
    return { total: 0, convertedAll: missing.length === 0, missingRateCurrencies: missing };
  }
  let total = 0;
  let convertedAll = true;
  const missingRateCurrencies = [];
  for (const entry of perCurrency) {
    if (!entry.currency) continue;
    if (entry.currency === baseCode) {
      total += entry.total;
      continue;
    }
    const rate = extractRate(rates.get(`${entry.currency}/${baseCode}`));
    if (rate !== null) {
      total += entry.total * rate;
    } else {
      convertedAll = false;
      if (!missingRateCurrencies.includes(entry.currency)) {
        missingRateCurrencies.push(entry.currency);
      }
    }
  }
  return { total: Math.round(total), convertedAll, missingRateCurrencies };
}
export {
  computeDelta,
  convertSumsToBase,
  getPreviousQuarterWindow,
  getQuarterWindow,
  getTrailingMonths
};
//# sourceMappingURL=dealsMetrics.js.map
