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

import { GENERATE_AIW_THUMBNAIL_OPTIONS } from '@/graphql/services/aiWorkbench/constants/thumbnail';

import { GENERATE_AIW_THUMBNAIL_OPTIONS_PAYLOAD } from '@/graphql/services/aiWorkbench/types/thumbnail/payload/generateThubnailOptions';

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

const queryGQL = `
  mutation ${GENERATE_AIW_THUMBNAIL_OPTIONS}($payload: ${GENERATE_AIW_THUMBNAIL_OPTIONS_PAYLOAD}) {
    ${GENERATE_AIW_THUMBNAIL_OPTIONS}(
      payload: $payload,
    )
  }
`;

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

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: {
            payload: {
              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 })));
          }

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

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