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

import { getSpeechToTextModelsAction, speechToTextModelsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getSpeechToTextModels {
    getSpeechToTextModels {
      data {
        model
        name
      }
    }
  }
`;

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

          if (!errors?.length) {
            actions.push(of(speechToTextModelsAction(data.getSpeechToTextModels?.data ?? [])));
          }

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

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