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_ACCOUNT_OPTIONS } from '@/graphql/services/feeds/constants';

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

import { getAccountOptionsAction, 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 = {
  searchText: string;
  pageSize: number;
};

const getResponse = (data: FeedType['account'][]) => data;

const query = `
  query ${GET_FEED_ACCOUNT_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_FEED_ACCOUNT_OPTIONS}(payload: $payload) {
      id
      name
      type
      contentOwners {
        type
        status
      }
    }
  }
`;

const getAccountOptionsEpic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getAccountOptionsAction> => action.type === getAccountOptionsAction.type,
    ),
    debounce((action) => {
      const { searchText } = action.payload;
      return timer(searchText.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const payload: PayloadType = {
        searchText: action.payload.searchText,
        pageSize: 30,
      };

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

export default getAccountOptionsEpic;
