import {
  CALENDAR_FILTER_VALUE,
  DIMENSIONS_LIST,
  DIMENSIONS_WITH_EXEPTIONS,
  FILTERS,
  HUB_FILTER_NAME,
  METRICS_VALUES,
  RECURRENCE_VALUES,
} from '../constants';

const getStateFromCustomReportRequestBody = ({ body, isDuplicate = false, userEmail, userPublisherIds }) => {
  const {
    name,
    period,
    periodCustomStartDate,
    periodCustomEndDate,
    metrics,
    dimensions,
    scheduled,
    scheduleType,
    scheduleValue,
    recipients,
    filters,
    createdBy,
  } = body;

  const state = {
    name: isDuplicate ? `Copy of ${name}`.substring(0, 200) : name,
    period,
    checkedMetrics: metrics?.filter((item) => METRICS_VALUES[item.name])?.map((item) => item.name),
  };

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

  if (scheduled && !isDuplicate) {
    state.scheduleType = scheduleType ?? null;
    state.scheduleTime = scheduleValue.time ?? null;
    state.recipients = recipients ?? [];

    if (scheduleType === RECURRENCE_VALUES.weekly.value) {
      state.scheduleDay = scheduleValue.dayInWeek ?? null;
    }

    if (scheduleType === RECURRENCE_VALUES.monthly.value) {
      state.scheduleDay = scheduleValue.dayInMonth ?? null;
    }
  }

  if (dimensions?.length) {
    const sortedDimensions = dimensions.sort((a, b) => a.order - b.order);
    const checkedDimensions = sortedDimensions?.filter((item) => item.value)?.map((item) => item.name);

    state.checkedDimensions = checkedDimensions;

    if (DIMENSIONS_LIST.length === sortedDimensions?.length) {
      state.dimensionsList = sortedDimensions.map((item) => DIMENSIONS_WITH_EXEPTIONS[item.name]);
    }
  }

  if (filters?.length && !isDuplicate) {
    filters.forEach((filter) => {
      if (filter.name === HUB_FILTER_NAME && !userPublisherIds?.includes(+filter.value)) {
        return;
      }

      if (FILTERS[filter.name]?.multiple) {
        state[`${filter.name}_FILTER_VALUES`] = [
          ...(state[`${filter.name}_FILTER_VALUES`] ?? []),
          {
            label: filter.label,
            value: filter.value,
          },
        ];
      } else {
        state[`${filter.name}_FILTER_VALUES`] = {
          label: filter.label,
          value: filter.value,
        };
      }

      state[`${filter.name}_FILTER_ACTION`] = filter.action;
    });
  }

  if (createdBy !== userEmail && !isDuplicate) {
    state.isReadOnly = true;
  } else {
    state.isReadOnly = false;
  }

  return state;
};

export default getStateFromCustomReportRequestBody;
