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

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

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

const getResponse = ({ data: { getEntitiesLanguages } }) =>
  getEntitiesLanguages.map((language) => ({
    value: language.id,
    label: language.name,
  }));

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

          return EMPTY;
        }),
      );

      return concat(
        of(
          setAction({
            languages: null,
          }),
        ),
        stream$,
      );
    }),
  );
