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

import { GET_XRAY_LINE_ITEM_GEO_OPTIONS } from '@/graphql/services/xRayLineItems/constants';

import { getGeographyOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_XRAY_LINE_ITEM_GEO_OPTIONS} {
    ${GET_XRAY_LINE_ITEM_GEO_OPTIONS} {
      records {
        id
        name
     }   
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_XRAY_LINE_ITEM_GEO_OPTIONS].records.map((o) => ({ label: o.name, value: o.id }));

export default (action$) =>
  action$.pipe(
    ofType(getGeographyOptionsAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              setAction({
                geographyOptions: getResponse(response),
              }),
            );
          }

          return EMPTY;
        }),
      );

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