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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

const queryGQL = `
  query AiWorkbenchGetHighlights($videoId: String!) {
    aiWorkbenchGetHighlights(videoId: $videoId) {
      published
      draft
      isGeneratingAvailable
      causes
      highlights {
        id
        start
        end
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getHighlightsAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const { shouldShowGenerationsCompletedNotification = false } = action.payload || {};

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

          if (!errors.length) {
            payload.highlights = response.highlights || [];
            payload.published = response.published;
            payload.draft = response.draft;
            payload.isGeneratingAvailable = response.isGeneratingAvailable;
            payload.causes = response.causes;

            if (shouldShowGenerationsCompletedNotification) {
              const message = payload.highlights.length
                ? `Highlights generation completed. ${payload.highlights.length} highlights were identified`
                : 'Highlights generation completed. No highlights were identified';

              actions.push(of(showNotificationAction({ type: TYPE_SUCCESS, message })));
            }
          }

          actions.push(of(setAction(payload)));

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

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