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 { getDemandSourcesAction, setAction } 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
    }
  }
`;

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

      const adFormat = adFormatSelector(state);

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

          if (!errors.length) {
            const { demandSources } = data.adPerformanceDemandSources;

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

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

export default epic;
