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

import { DELETE_ALL_VIDEOS } from '@/graphql/services/accounts/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/accounts/types/payload/deleteAllVideos';

import { deleteAllVideos } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `mutation ${DELETE_ALL_VIDEOS}($payload: ${PAYLOAD_NAME}) {
  ${DELETE_ALL_VIDEOS}(payload: $payload)
}`;

export default (action$) =>
  action$.pipe(
    ofType(deleteAllVideos.type),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: payload,
          },
        },
      }).pipe(switchMap(() => EMPTY));

      return concat(
        of(
          showNotificationAction({
            type: TYPE_SUCCESS,
            message: 'Initiated a deletion of all account videos',
          }),
        ),
        stream$,
      );
    }),
  );
