import { eachHourOfInterval } from 'date-fns';
import { TimePerTourMetric } from '../../../core/data-access/graphql/generated/generated';

export function summarizeMetrics(
  metrics: TimePerTourMetric[]
): TimePerTourMetric {
  const metricInterval = {
    start: new Date(metrics[0].interval.start),
    end: new Date(metrics[0].interval.end),
  };
  return {
    ...metrics.reduce(
      (sum, metric) => ({
        ...sum,
        interval: metricInterval,
        availableTime: sum.availableTime + metric.availableTime,
        tourAmount: sum.tourAmount + metric.tourAmount,
        breakEven: sum.breakEven + metric.breakEven,
        revenue: sum.revenue + metric.revenue,
        personnelCost: sum.personnelCost + metric.personnelCost,
        consumptionCost: sum.consumptionCost + metric.consumptionCost,
        forecast:
          eachHourOfInterval(metricInterval).length <= 1
            ? metric.forecast
            : Math.round(sum.forecast) + Math.round(metric.forecast),
        forecastRevenue:
          eachHourOfInterval(metricInterval).length <= 1
            ? metric.forecastRevenue
            : sum.forecastRevenue + metric.forecastRevenue,
      }),
      {
        interval: { start: new Date(), end: new Date() },
        availableTime: 0,
        tourAmount: 0,
        breakEven: 0,
        revenue: 0,
        averageRevenue: 0,
        personnelCost: 0,
        consumptionCost: 0,
        forecast: 0,
        forecastRevenue: 0,
        categoryAmounts: [],
      }
    ),
    averageRevenue:
      metrics.reduce((sum, { averageRevenue }) => (sum += averageRevenue), 0) /
        metrics.filter(({ averageRevenue }) => averageRevenue > 0).length || 0,
  };
}
