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

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { getCcSegmentsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query AiWorkbenchGetCcSegments($videoId: String!) {
    aiWorkbenchGetCcSegments(videoId: $videoId) {
      data {
        uid
        transcript
        provider
        speakerId
        startTime
        endTime
        tokens {
          startTime
          endTime
          word
          kind
          confidence
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getCcSegmentsAction.type),
    switchMap(() => {
      const video = selectedVideoSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setAction({ ccSegments: data?.aiWorkbenchGetCcSegments?.data || [] })));
          }

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

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
