import { AvropPeriod } from '@msfa-models/avrop-period.model';
import { addMonths, endOfMonth, formatISO, startOfMonth, subMonths } from 'date-fns';

export function dateToPeriodId(date: Date): string {
  return formatISO(date).slice(0, 7);
}

export function extractAvropPeriods(avropStartDate: Date, avropEndDate: Date): AvropPeriod[] {
  const today = new Date();

  if (avropStartDate > today) {
    throw new Error('Avropet har inte börjat ännu.');
  }
  if (avropStartDate > avropEndDate) {
    throw new Error('Avropets startdatum måste komma innan slutdatumet.');
  }

  const previousPeriod = dateToPeriodId(today >= avropEndDate ? avropEndDate : subMonths(today, 1));
  const periods: AvropPeriod[] = [] as AvropPeriod[];
  let dateCounter = avropStartDate;

  while (dateCounter <= avropEndDate && dateToPeriodId(dateCounter) <= previousPeriod) {
    const startDate = dateCounter === avropStartDate ? avropStartDate : startOfMonth(dateCounter);
    const endDate = endOfMonth(dateCounter) > avropEndDate ? avropEndDate : endOfMonth(dateCounter);
    const period: AvropPeriod = { startDate, endDate, periodId: dateToPeriodId(dateCounter) };
    periods.push(period);
    dateCounter = startOfMonth(addMonths(dateCounter, 1));
  }
  return periods;
}
