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

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

import videosQuery from '@/modules/@common/gql/queries/videos';

const query = videosQuery;

const getResponse = ({ data: { videoSearch } }) =>
  videoSearch.videos.map((video) => ({ value: video.uid, label: video.name }));

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

      const stream$ = gqlRequest({
        query,
        variables: {
          query: action.payload ?? '',
          typeValue: 'SHORT_FORM',
          videoAffiliation: 'ALL_VIDEOS',
          page: 0,
          queryIds: true,
          includeMaxPerformance: true,
          origins: {
            exclude: true,
            value: 'RSS',
          },
          sortOrder: 'DESC',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions: getResponse(response),
                  },
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
