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

import { GET_USERS_FOR_SHARE_ACTION } from '@/graphql/services/videoBulkActions/constants';

import { PAYLOAD_NAME } from '@/graphql/services/videoBulkActions/types/payload/user';

import { getUserOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_USERS_FOR_SHARE_ACTION}($payload: ${PAYLOAD_NAME}) {
    ${GET_USERS_FOR_SHARE_ACTION}(payload: $payload) {
      records {
        id
        email
        firstName
        lastName
     }   
    }
  }
`;

const getResponse = ({ data }) => data[GET_USERS_FOR_SHARE_ACTION].records;

export default (action$) =>
  action$.pipe(
    ofType(getUserOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText: action.payload ?? '',
            pageSize: 30,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                userOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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