/* eslint-disable implicit-arrow-linebreak */
import type { CalculationValues } from 'stores/calculation/values/types';
import { SEASONS_PERIODS, SEASONS_PERIOD_NUMBER } from './seasons-constants';

type SeasonType = NonNullable<CalculationValues['seasonType']>;
type LeasingPeriod = CalculationValues['leasingPeriod'];

export function getPositionIndex(seasonType: SeasonType, seasonsIndex: number) {
  let positionIndex = 0;

  SEASONS_PERIODS[seasonType].forEach((position, i) => {
    if (seasonsIndex >= position) {
      positionIndex = i;
    }
  });

  return positionIndex;
}

export function getSeasonsValues(seasonType: SeasonType, seasons: Array<number>) {
  return SEASONS_PERIODS[seasonType].map((index) => seasons[index]);
}

export function generateSeasons(seasonType: SeasonType, values: Array<number>) {
  const positions = SEASONS_PERIODS[seasonType];

  const seasons: Array<number> = [];

  [...positions, SEASONS_PERIOD_NUMBER].forEach((position, i, arr) => {
    if (position < SEASONS_PERIOD_NUMBER) {
      const start = arr[i];
      const end = arr[i + 1];
      const value = values[i];

      // eslint-disable-next-line unicorn/new-for-builtins
      seasons.push(...Array(end - start).fill(value));
    }
  });

  return seasons;
}

export function generateSeasonsPayments(leasingPeriod: LeasingPeriod, seasons: Array<number>) {
  return (
    Array.from(
      {
        length: Math.floor((leasingPeriod - 2) / SEASONS_PERIOD_NUMBER),
      },
      () => seasons
    )
      .flat()
      // eslint-disable-next-line unicorn/prefer-spread
      .concat(seasons.slice(0, (leasingPeriod - 2) % SEASONS_PERIOD_NUMBER))
  );
}
