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

const queryGQL = `
  query AiWorkbenchGetDescriptionQuery(
    $videoId: String!,
  ) {
    aiWorkbenchGetDescription(
      videoId: $videoId,
    ) {
      published
      draft
      description
      descriptions {
        type
        value
      }
      isGeneratingAvailable
      causes
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getDescriptionAction.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.aiWorkbenchGetDescription;
          const descriptions = response?.descriptions ?? [];

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

            if (shouldShowGenerationsCompletedNotification) {
              const message = descriptions.length
                ? 'Description options successfully generated'
                : 'Description generation completed. No descriptions were identified';

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

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

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