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

import * as watchesSelectors from '../selectors';
import { deleteWatchAction, setWatchesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation DeleteWatch($id: Int!) {
    deleteWatch(id: $id){
      id
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(deleteWatchAction.type),
    switchMap(({ payload: { id } }) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            const watches = watchesSelectors.watchesSelector(state$.value);
            const newWatches = watches.filter((watch) => watch.id !== id);
            actions.push(of(setWatchesAction(newWatches)));
          }

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

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