import { CALENDAR_FILTER_VALUE, FILTERS_LIST, RECURRENCE_VALUES } from '../constants';

import * as selectors from '../redux/selectors';

const createCustomReportRequestBody = (state) => {
  const name = selectors.nameSelector(state);
  const period = selectors.periodSelector(state);
  const periodCustomStartDate = selectors.periodCustomStartDateSelector(state);
  const periodCustomEndDate = selectors.periodCustomEndDateSelector(state);
  const checkedMetrics = selectors.checkedMetricsSelector(state);
  const dimensionsList = selectors.dimensionsListSelector(state);
  const checkedDimensions = selectors.checkedDimensionsSelector(state);
  const scheduleType = selectors.scheduleTypeSelector(state);
  const scheduleDay = selectors.scheduleDaySelector(state);
  const scheduleTime = selectors.scheduleTimeSelector(state);
  const recipients = selectors.recipientsSelector(state);
  const filters = selectors.filtersSelector(state);

  const body = {
    name,
    period,
    metrics: checkedMetrics?.map((item) => ({ name: item, value: true })),
    dimensions: dimensionsList?.map((item, index) => ({
      name: item?.value,
      value: checkedDimensions?.includes(item?.value),
      order: index,
    })),
  };

  if (period === CALENDAR_FILTER_VALUE.custom) {
    body.periodCustomStartDate = periodCustomStartDate;
    body.periodCustomEndDate = periodCustomEndDate;
  }

  if (!scheduleType || !recipients?.length) {
    body.scheduled = false;
  } else if (scheduleType === RECURRENCE_VALUES.daily.value) {
    body.scheduled = true;
    body.scheduleType = scheduleType;
    body.scheduleValue = {
      time: scheduleTime,
    };
    body.recipients = recipients;
  } else if (scheduleType === RECURRENCE_VALUES.weekly.value) {
    body.scheduled = true;
    body.scheduleType = scheduleType;
    body.scheduleValue = {
      dayInWeek: scheduleDay,
      time: scheduleTime,
    };
    body.recipients = recipients;
  } else {
    body.scheduled = true;
    body.scheduleType = scheduleType;
    body.scheduleValue = {
      dayInMonth: scheduleDay,
      time: scheduleTime,
    };
    body.recipients = recipients;
  }

  const filtersBody = FILTERS_LIST.reduce((acc, cur) => {
    const valuesFromProps = filters[`${cur.name}_FILTER_VALUES`];
    const values = Array.isArray(valuesFromProps) ? valuesFromProps : [valuesFromProps]; // some filter is not multiple
    if (valuesFromProps && values?.length) {
      const fullInfoValues = values.map((item) => ({
        action: filters[`${cur.name}_FILTER_ACTION`],
        name: cur.name,
        value: item.value?.toString(),
        label: item.label,
      }));
      return [...acc, ...fullInfoValues];
    }
    return acc;
  }, []);

  body.filters = filtersBody;

  return body;
};

export default createCustomReportRequestBody;
