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

import { CHART_TIME_INTERVAL_TAB } from '../../constants';

import * as selectors from '../selectors';
import { getHistoryForChartAction, setChartTabAction, setFieldAction, setTimeIntervalFilterAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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(getHistoryForChartAction.type, setChartTabAction.type, setTimeIntervalFilterAction.type),
    filter(() => {
      const state = state$.value;

      const chartTab = selectors.chartTabSelector(state);

      return chartTab === CHART_TIME_INTERVAL_TAB;
    }),
    switchMap(() => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);
      const timeIntervalFilter = selectors.timeIntervalFilterSelector(state);

      const { interval, dimension, ...range } = timeIntervalFilter;

      const stream$ = gqlRequest({
        query,
        variables: {
          ids: [pageConfig.id],
          range,
          graphMode: true,
          order: 'DESC',
          size: 1000,
          excludeAuto: false,
          actions: [
            'PRICING_LINE_ITEM_ADD',
            'TIER_CHANGE',
            'PRIORITY_CHANGE',
            'AD_SERVER_URL_CHANGE',
            'TIMEOUT_CHANGE',
            'NEW_RATE_CREATION',
            'NEW_ADDITIONAL_FEES_CREATION',
            'ANY_TARGETING_CHANGE',
            'ANY_FREQUENCY_CAP_CHANGE',
            'ANY_BUDGETING_CHANGE',
            'ANY_SPECIFIC_PARAMETER_CHANGE',
            'AI_DEFAULT_FLOOR_MANAGEMENT',
            'DEFAULT_HB_FLOR_VIEWABLE_CHANGE',
            'DEFAULT_HB_FLOR_NON_VIEWABLE_CHANGE',
            'AUTOMATIC_OPTIMIZATION_STATUS_CHANGE',
            'TARGET_KPI_CHANGE',
            'DEFAULT_HB_FLOR_FIRST_REQUEST_CHANGE',
            'AUTOMATIC_FLOOR_PRICE_STATUS_CHANGE',
          ],
        },
      }).pipe(
        switchMap(({ data = {}, errors }) => {
          let actions = [];

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

            actions = [of(setFieldAction({ chartHistory: response.data }))];
          }

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

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