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_CLIENT_ID } from '@/graphql/services/feeds/constants';
import { OAUTH_CLIENT_IDS_PAYLOAD_MAPPER } from '@/modules/feeds/Editor/components/FormElements/Authorization/constants';

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

import { typeSelector } from '../selectors';
import { getOAuthClientIdAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';

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

export type PayloadType = {
  type: (typeof OAUTH_CLIENT_IDS_PAYLOAD_MAPPER)[OAuthFeedType];
};

type ResType = {
  clientId: string;
};

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

const query = `
  query ${GET_OAUTH_CLIENT_ID}($payload: ${PAYLOAD_NAME}) {
    ${GET_OAUTH_CLIENT_ID}(payload: $payload) {
      clientId
    }
  }
`;

const getHubsOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getOAuthClientIdAction> =>
        action.type === getOAuthClientIdAction.type && typeSelector(state$.value) in OAUTH_CLIENT_IDS_PAYLOAD_MAPPER,
    ),
    switchMap(() => {
      const type = typeSelector(state$.value) as OAuthFeedType;
      const payload: PayloadType = { type: OAUTH_CLIENT_IDS_PAYLOAD_MAPPER[type] };

      return gqlRequest({
        query,
        variables: { payload },
      }).pipe(
        switchMap((response: GraphQLResponse<typeof GET_OAUTH_CLIENT_ID, ResType>) => {
          if (!response.errors.length) {
            return of(
              setAction({
                oAuthClientId: getResponse(response.data[GET_OAUTH_CLIENT_ID]).clientId,
              }),
            );
          }
          return EMPTY;
        }),
      );
    }),
  );

export default getHubsOptionsEpic;
