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

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

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

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

      const countriesFullList = selectors.countriesFullListSelector(state);
      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,
          size: 250,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { countries } = data.adPerformanceCountries;

            actions.push(
              of(
                setFieldAction({
                  countriesOptions:
                    countries?.map((code) => ({
                      label: countriesFullList?.find((item) => item.uiKey === code)?.name ?? code,
                      value: code,
                    })) ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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