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

import { IMPORT_ARCHIVED_SELF_SERVE_FEEDS } from '@/graphql/services/feeds/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/selfserve/importArchived';

import { importArchivedAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

const query = `
  mutation ${IMPORT_ARCHIVED_SELF_SERVE_FEEDS}($payload: ${PAYLOAD_NAME}) {
    ${IMPORT_ARCHIVED_SELF_SERVE_FEEDS}(payload: $payload)
  }
`;

const importArchived: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof importArchivedAction> => action.type === importArchivedAction.type),
    switchMap((action) => {
      const $stream = gqlRequest({
        query,
        variables: { payload: action.payload },
      }).pipe(
        switchMap((response: GraphQLResponse<typeof IMPORT_ARCHIVED_SELF_SERVE_FEEDS, unknown>) => {
          if (!response.errors.length) {
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Your recordings are being imported into AnyClip.',
                }),
              ),
            );
          }
          return EMPTY;
        }),
      );

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

export default importArchived;
