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

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

import { getDemandSourcesAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query adPerformanceDemandSources(
    $devices: [String],
    $domains: [String],
    $countries: [String],
    $dateRange: AnalyticsDateRangeInputType,
    $interval: AnalyticsIntervalInputType,
    $timezone: String,
    $prefix: String,
    $size: Int
  ) {
    adPerformanceDemandSources(
      devices: $devices,
      domains: $domains,
      countries: $countries,
      dateRange: $dateRange,
      interval: $interval,
      timezone: $timezone,
      prefix: $prefix,
      size: $size
    ) {
      rid
      demandSources
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getDemandSourcesAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap((action) => {
      let requestParams = {};

      if (action.payload?.length) {
        requestParams = {
          prefix: action.payload,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          size: 100,
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { demandSources } = data.adPerformanceDemandSources;

            actions.push(
              of(
                setFieldAction({
                  [`${DEMAND_SOURCE_FILTER_NAME}_FILTER_OPTIONS`]:
                    demandSources?.map((item) => ({ label: item, value: item })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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