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

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

const queryGQL = `
  mutation DeleteChannel($watchId: Int!, $id: Int!) {
    deleteChannel(watchId: $watchId, id: $id){
      id
    }
  }
`;

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

          if (!errors.length) {
            const watches = watchesSelectors.watchesSelector(state$.value);

            const newWatches = watches.map((watch) => {
              if (watch.id === watchId) {
                const watchChannels = watch.watchChannels.filter((channel) => channel.id !== id);

                return {
                  ...watch,
                  watchChannels,
                };
              }

              return watch;
            });

            actions.push(of(setWatchesAction(newWatches)));
          }

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

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