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

import * as selectors from '../selectors';
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,
    $adFormat: String,
    $size: Int
  ) {
    adPerformanceDemandSources(
      devices: $devices,
      domains: $domains,
      countries: $countries,
      dateRange: $dateRange,
      interval: $interval,
      timezone: $timezone,
      prefix: $prefix,
      adFormat: $adFormat,
      size: $size
    ) {
      rid
      demandSources
    }
  }
`;

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

      const adFormat = selectors.adFormatSelector(state);

      let requestParams = {};

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

      if (adFormat) {
        requestParams = {
          ...requestParams,
          adFormat,
        };
      }

      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({
                  demandSourcesOptions: demandSources?.map((item) => ({ label: item, value: item })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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