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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { watchesSelector } from '../selectors';
import { copyChannelAction, copyWatchChannelAction, getWatchesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  query CopyWatchChannel(
    $fromChannelId: Int!,
    $toWatchId: Int!,
  ) {
    copyWatchChannel(
      fromChannelId: $fromChannelId,
      toWatchId: $toWatchId,
    ) {
      id
      title
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(copyWatchChannelAction.type),
    mergeMap(({ payload: { fromChannelId, toWatchId } }) => {
      const watches = watchesSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          fromChannelId,
          toWatchId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const targetWatch = watches.find((watch) => watch.id === toWatchId);
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: `Channel pasted as ${data.copyWatchChannel.title} into the ${targetWatch.title} Watch`,
                }),
              ),
              of(copyChannelAction()),
              of(getWatchesAction()),
            );
          }

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

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