import { ofType } from 'redux-observable';
import { concat, EMPTY, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { gqlRequest } from '@/modules/@common/request';

export default function createEpicGetData({
  gqlQuery,
  triggerActionType,
  processBodyRequest,
  processResponse,
  setTableAction,
}) {
  return (action$, state$) =>
    action$.pipe(
      ofType(triggerActionType),
      switchMap((action) => {
        const stream$ = gqlRequest({
          query: gqlQuery,
          variables: processBodyRequest(state$.value, action.payload),
        }).pipe(
          switchMap((response) => {
            if (!response.errors.length) {
              const data = processResponse(response);

              return of(
                setTableAction({
                  data: data.records,
                  totalCount: data.recordsTotal,
                  // value for know how many relevant rows there are in DB for sure when to show Empty table Screen
                  allRecordsCount: data.allRecordsCount || data.recordsTotal,
                  isLoading: false,
                }),
              );
            }

            return EMPTY;
          }),
        );

        return concat(of(setTableAction({ isLoading: true })), stream$);
      }),
    );
}
