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 { attachIdToChapters } from '../../helpers';
import { getChaptersAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  query AiWorkbenchGetChaptersQuery(
    $videoId: String!,
  ) {
    aiWorkbenchGetChapters(
      videoId: $videoId,
    ) {
      published
      draft
      isGeneratingAvailable
      causes
      chapters {
        time
        name
        description
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getChaptersAction.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 actions = [];
          const response = data.aiWorkbenchGetChapters;
          const chapters = response?.chapters ?? [];

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  chapters: attachIdToChapters(chapters),
                  published: response.published,
                  draft: response.draft,
                  isLoading: false,
                  isGeneratingAvailable: response.isGeneratingAvailable,
                  causes: response.causes,
                }),
              ),
            );

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

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

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

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