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

import { searchSuggesterAction, suggesterOptionsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import { getUserContentOwnerIdsSelector } from '@/modules/@common/user/redux/selectors';

const queryGQL = `
  query autocomplete(
    $prefix: String!,
    $size: Int,
    $videoType: String,
    $videoStatus: String,
    $contentOwner: Int,
    $contentOwners: [Int]!,
    $includeOrigin: String,
    $excludeOrigin: String
    ) {
      autocompleteVideoNames(
        prefix: $prefix,
        size: $size,
        videoType: $videoType,
        videoStatus: $videoStatus,
        contentOwner: $contentOwner,
        contentOwners: $contentOwners,
        includeOrigin: $includeOrigin,
        excludeOrigin: $excludeOrigin
      ) {
        value
        count
      }
    }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(searchSuggesterAction.type),
    filter((action) => !!getToken() && !!action.payload),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          prefix: action.payload.prefix ?? '',
          size: 10,
          contentOwners: getUserContentOwnerIdsSelector(state$.value),
          excludeOrigin: 'RSS',
          videoType: 'SHORT_FORM',
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                suggesterOptionsAction(
                  !action.payload?.clearSuggestions ? data.autocompleteVideoNames.map(({ value }) => value) : [],
                ),
              ),
            );
          }

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

      return stream$;
    }),
  );
