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

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

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

const queryGQL = `
  mutation AiWorkbenchGenerateHighlightsByAiQuery(
    $videoId: String!,
    $notifyByEmail: Boolean!
  ) {
    aiWorkbenchGenerateHighlightsByAi(
      videoId: $videoId,
      notifyByEmail: $notifyByEmail,
    )
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(generateByAiAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: {
            videoId: video.uid,
            notifyByEmail: action.payload,
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap(({ errors }) => {
          const actions = [of(setAction({ isLoading: false }))];

          if (!errors?.length) {
            actions.push(of(monitoringStartAction()));
            actions.push(of(setAction({ processing: true })));
          } else {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_WARNING,
                  message: errors[0].message,
                }),
              ),
            );
          }

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

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