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

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

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

const queryGQL = `
  mutation videoDeletePublishEntry(
    $videoId: String!,
    $destinations: [String],
    ) {
      videoDeletePublishEntry(
      videoId: $videoId,
      destinations: $destinations,
      ) {
        data {
          id
        }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(deletePublishEntriesAction.type),
    switchMap((action) => {
      const { entries, videoId } = action.payload;

      const paramsToSend = entries.map((entry) => entry.id);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          destinations: [...paramsToSend],
          videoId,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: `${entries.length > 1 ? 'Entries' : 'Entry'} removed`,
                }),
              ),
              of(getPublishEntriesAction(videoId)),
            );
          }

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

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