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

import { loadTranslateLanguagesAction, setTranslateLanguagesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getTranslateLanguages {
    getTranslateLanguages {
      id
      name
    }
  }
`;

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

          if (!errors.length) {
            actions.push(of(setTranslateLanguagesAction(data.getTranslateLanguages)));
          }

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

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