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

import { getMenuItemsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetGeneralAnalyticsMenuItems {
    getGeneralAnalyticsMenuItems {
      records {
        name
        lookerReportId
        type
      }  
    }
  }
`;

const getResponse = ({ data: { getGeneralAnalyticsMenuItems } }) => getGeneralAnalyticsMenuItems;

export default (action$) =>
  action$.pipe(
    ofType(getMenuItemsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);

            return of(
              setFieldAction({
                menu: data.records,
              }),
            );
          }

          return EMPTY;
        }),
      );

      return concat(stream$);
    }),
  );
