import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

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

import { PublishEntryType } from '../../types';

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

import type { RootState } from '@/modules/@common/store/store';

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

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof deletePublishEntriesAction> =>
        action.type === deletePublishEntriesAction.type,
    ),
    switchMap((action) => {
      const { entries, videoId } = action.payload;

      const paramsToSend = entries.map((entry: PublishEntryType) => 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$);
    }),
  );

export default epic;
