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

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

import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/feedItem';
import type { FeedType } from '@/modules/feeds/types';

import * as selectors from '../selectors';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getRequestPayload } from '@/modules/feeds/Editor/helpers/requestPayload';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

type ResponseType = {
  data: {
    id: number;
  };
  errors: unknown[];
};

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

const getAccountOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof createItemAction> => action.type === createItemAction.type),
    switchMap(() => {
      const type = selectors.typeSelector(state$.value) as FeedType;
      const payload = getRequestPayload(type, state$.value);

      return gqlRequest({
        query,
        variables: { payload },
      }).pipe(
        switchMap((response: ResponseType) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Feed created successfully',
                }),
              ),
            );

            Router.push('/feeds');
          }

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

export default getAccountOptionsEpic;
