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

import * as selectors from '../selectors';
import { getGeoOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query Query {
    commonGeography {
      id
      uiKey
      name
    }
  }
`;

const getResponse = ({ data: { commonGeography } }) =>
  commonGeography.map((geo) => ({ value: geo.uiKey, label: geo.name }));

export default (action$, state$) =>
  action$.pipe(
    ofType(getGeoOptionsAction.type),
    switchMap(() => {
      const autocomplete = selectors.autocompleteSelector(state$.value);

      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions: getResponse(response),
                  },
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
