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

import { queryParamsSelector } from '../selectors';
import { archiveLiveEventsAction, getLiveEventsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

const queryGQL = `
  mutation liveEventsArchive($ids: [Int]) {
    liveEventsArchive(ids: $ids) {
      result {
        status
        message
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(archiveLiveEventsAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          ids: action.payload,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            const query = queryParamsSelector(state$.value);
            actions.push(of(getLiveEventsAction(query)));
          }

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

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