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

import { targetVideoIdSelector } from '../selectors';
import {
  isTargetClipIdLoadingAction,
  targetClipIdAction,
  targetClipIdEventAction,
  targetVideoIdAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const clipsQuery = `
query video($id: String!) {
  video(id: $id) {
    distributionId
  }
}
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(targetVideoIdAction.type),
    filter(() => targetVideoIdSelector(state$.value)),
    mergeMap(() => {
      const state = state$.value;
      const targetVideoId = targetVideoIdSelector(state);

      const stream$ = gqlRequest({
        query: clipsQuery,
        variables: {
          id: targetVideoId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(targetClipIdAction(data.video.distributionId)));
            actions.push(of(targetClipIdEventAction()));
          }

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

      return concat(of(isTargetClipIdLoadingAction(true)), stream$, of(isTargetClipIdLoadingAction(false)));
    }),
  );
