import { ofType } from 'redux-observable';
import { concat } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

import { createHistoryCSV } from '../../helpers/createHistoryCSV';
import * as selectors from '../selectors';
import { getHistoryForCSVAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query MarketplaceHistory(
    $from: Int,
    $size: Int,
    $ids: [String],
    $actions: [String],
    $types: [String],
    $range: MarketplaceFiltersRangesInputType,
    $graphMode: Boolean,
    $excludeAuto: Boolean,
    $order: String
  ) {
    marketplaceHistory(
      from: $from,
      size: $size,
      ids: $ids,
      actions: $actions,
      types: $types,
      range: $range,
      graphMode: $graphMode,
      excludeAuto: $excludeAuto,
      order: $order
    ) {
      totalCount
      data {
        id
        created
        ids
        type
        values {
          action
          actionWithName
          name
          changes {
            name
            oldValue
            newValue
          }
        }
        updatedBy
        user {
          email
          firstName
          lastName
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getHistoryForCSVAction.type),
    filter(() => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);

      return !!pageConfig;
    }),
    switchMap(() => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);
      const filterByDate = selectors.filterByDateSelector(state);

      const userTimezone = getUserTimezoneSelector(state);

      const { isCustomPeriod, ...filterByDateRest } = filterByDate;
      const { change, dimension, changeDimension, ...range } = filterByDateRest;

      const stream$ = gqlRequest({
        query,
        variables: {
          ids: [pageConfig.id],
          range,
          graphMode: false,
          order: 'DESC',
          size: 1000,
        },
      }).pipe(
        switchMap(({ data = {}, errors }) => {
          const actions = [];

          if (!errors.length) {
            const response = {
              ...data.marketplaceHistory,
            };

            createHistoryCSV({
              pageConfig,
              data: response.data,
              userTimezone,
            });
          }

          return concat(...actions);
        }),
      );

      return concat(stream$);
    }),
  );
