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

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

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

      const adFormat = adFormatSelector(state);

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

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

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

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

export default epic;
