/*
 This file is part of GNU Taler
 (C) 2022-2025 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */
import { AbsoluteTime, assertUnreachable } from "@gnu-taler/taler-util";
import { sub } from "date-fns";
import { TalerCorebankApi } from "@gnu-taler/taler-util";

export type Timeframe = { start: AbsoluteTime; end: AbsoluteTime };

export function getTimeframesForDate(
  time: Date,
  timeframe: TalerCorebankApi.MonitorTimeframeParam,
): {
  current: Timeframe;
  previous: Timeframe;
} {
  switch (timeframe) {
    case TalerCorebankApi.MonitorTimeframeParam.hour: {
      const [high, middle, low] = [0, 1, 2].map((timeIndex) =>
        AbsoluteTime.fromMilliseconds(
          sub(time, { hours: timeIndex }).getTime(),
        ),
      );
      return {
        current: { start: middle, end: high },
        previous: { start: low, end: middle },
      };
    }
    case TalerCorebankApi.MonitorTimeframeParam.day: {
      const [high, middle, low] = [0, 1, 2].map((timeIndex) =>
        AbsoluteTime.fromMilliseconds(sub(time, { days: timeIndex }).getTime()),
      );
      return {
        current: { start: middle, end: high },
        previous: { start: low, end: middle },
      };
    }
    case TalerCorebankApi.MonitorTimeframeParam.month: {
      const [high, middle, low] = [0, 1, 2].map((timeIndex) =>
        AbsoluteTime.fromMilliseconds(
          sub(time, { months: timeIndex }).getTime(),
        ),
      );
      return {
        current: { start: middle, end: high },
        previous: { start: low, end: middle },
      };
    }

    case TalerCorebankApi.MonitorTimeframeParam.year: {
      const [high, middle, low] = [0, 1, 2].map((timeIndex) =>
        AbsoluteTime.fromMilliseconds(
          sub(time, { years: timeIndex }).getTime(),
        ),
      );
      return {
        current: { start: middle, end: high },
        previous: { start: low, end: middle },
      };
    }
    case TalerCorebankApi.MonitorTimeframeParam.decade: {
      const [high, middle, low] = [0, 1, 2].map((timeIndex) =>
        AbsoluteTime.fromMilliseconds(
          sub(time, { years: timeIndex * 10 }).getTime(),
        ),
      );
      return {
        current: { start: middle, end: high },
        previous: { start: low, end: middle },
      };
    }
    default:
      assertUnreachable(timeframe);
  }
}
