import { type Epic } from 'redux-observable';
import { concat, of, timer } from 'rxjs';
import { debounce, filter, mergeMap, switchMap } from 'rxjs/operators';
import type { Action } from '@reduxjs/toolkit';

import { adFormatSelector, countriesFullListSelector } from '../selectors';
import { getCountriesAction, setAction } 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
    }
  }
`;

const epic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getCountriesAction> => action.type === getCountriesAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    mergeMap((action) => {
      const adFormat = adFormatSelector(state$.value);

      const stream = gqlRequest({
        query,
        variables: {
          size: 250,
          prefix: action.payload || undefined,
          adFormat: adFormat || undefined,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions$ = [];

          if (!errors.length) {
            const countriesFullList = countriesFullListSelector(state$.value);

            const { countries } = data.adPerformanceCountries;

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

      return concat(stream);
    }),
  );

export default epic;
