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

import { COUNTRY_FILTER_NAME } from '../../constants';

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

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

export default (action$) =>
  action$.pipe(
    ofType(getCountriesAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(
                setFieldAction({
                  [`${COUNTRY_FILTER_NAME}_FILTER_OPTIONS`]:
                    data?.commonGeography?.map((item) => ({
                      label: item.name,
                      value: item.uiKey,
                    })) ?? [],
                }),
              ),
            ];
          }

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

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