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

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

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

import { accountSelector, isSelfServeUserSelector } from '../selectors';
import { getHubsOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';
import { getUserAccountIdSelector } from '@/modules/@common/user/redux/selectors';

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

export type PayloadType = {
  searchText: string;
  pageSize: number;
  accountId: number;
};

type HubType = {
  id: number;
  name: string;
};

const getResponse = (data: HubType[]) => data;

const query = `
  query ${GET_FEED_HUBS_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_FEED_HUBS_OPTIONS}(payload: $payload) {
      id
      name
    }
  }
`;

const getHubsOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getHubsOptionsAction> => action.type === getHubsOptionsAction.type),
    debounce((action) => {
      const { searchText } = action.payload;
      return timer(searchText.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const isSelfServeUser = isSelfServeUserSelector(state$.value);
      const userAccountId = getUserAccountIdSelector(state$.value);
      const accountId = accountSelector(state$.value)?.id;
      const payload: PayloadType = {
        searchText: action.payload.searchText,
        pageSize: 30,
        accountId: isSelfServeUser ? +userAccountId! : accountId!,
      };

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

export default getHubsOptionsEpic;
