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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(getDomainsAction.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: {
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { domains } = data.adPerformanceDomains;

            actions.push(
              of(
                setFieldAction({
                  domainsOptions: domains?.map((item) => ({ label: item, value: item })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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