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

import { GET_OAUTH_TOKEN } from '@/graphql/services/feeds/constants';

import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/feedItem';
import { OAuthFeedType } from '@/modules/feeds/Editor/components/FormElements/Authorization/types';

import { typeSelector } from '../selectors';
import { getOAuthTokenAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';
import { getRequestPayload } from '@/modules/feeds/Editor/helpers/requestPayload';

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

export type PayloadType = {
  code: string;
  type: OAuthFeedType;
};

type ResType = {
  token: string;
};

const getResponse = (data: ResType) => data;

const query = `
  query ${GET_OAUTH_TOKEN}($payload: ${PAYLOAD_NAME}) {
    ${GET_OAUTH_TOKEN}(payload: $payload) {
      token
    }
  }
`;

const getHubsOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getOAuthTokenAction> => action.type === getOAuthTokenAction.type),
    switchMap((action) => {
      const { code } = action.payload;
      const type = typeSelector(state$.value) as OAuthFeedType;
      const body = getRequestPayload(type, state$.value);
      const payload = { code, ...body };

      return gqlRequest({
        query,
        variables: { payload },
      }).pipe(
        switchMap((response: GraphQLResponse<typeof GET_OAUTH_TOKEN, ResType>) => {
          if (!response.errors.length) {
            return of(
              setAction({
                oAuthToken: getResponse(response.data[GET_OAUTH_TOKEN]).token,
                source: {
                  isConnected: true,
                },
              }),
            );
          }
          return EMPTY;
        }),
      );
    }),
  );

export default getHubsOptionsEpic;
