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

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

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

const query = `
  query ${GET_XRAY_LINE_TIMEZONE_OPTIONS} {
    ${GET_XRAY_LINE_TIMEZONE_OPTIONS} {
      records {
        id
        name
        displayName
     }   
    }
  }
`;

const getResponse = ({ data }) => data[GET_XRAY_LINE_TIMEZONE_OPTIONS].records;

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

          return EMPTY;
        }),
      );

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