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

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

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

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

          if (!errors.length) {
            actions = [
              of(
                setFieldAction({
                  countriesFullList: data?.commonGeography ?? [],
                }),
              ),
              of(getCountriesAction()),
            ];
          }

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

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