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

import { getCcTotalSegmentsAction, setCcTotalSegmentsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getCcTotalSegments($videoId: String!) {
    getCcTotalSegments(videoId: $videoId) {
      totalCount
    }
  }
`;

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

          if (!errors.length) {
            actions.push(of(setCcTotalSegmentsAction(data?.getCcTotalSegments?.totalCount)));
          }

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

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