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

import { JOB_TYPE_THUMBNAIL_PROCESSING, JOB_TYPE_THUMBNAILS_PUBLISHING } from '../../constants';
import { GET_AIW_THUMBNAIL_DATA } from '@/graphql/services/aiWorkbench/constants/thumbnail';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

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

const queryGQL = `
  query ${GET_AIW_THUMBNAIL_DATA}($payload: ${GET_AIW_THUMBNAIL_PAYLOAD} ) {
    ${GET_AIW_THUMBNAIL_DATA}(payload: $payload) {
      published
      draft
      draftPreview {
        uid
        url
      }
      thumbnailOptions {
        uid
        url
      }
      isGeneratingAvailable
      causes
    }
  }
`;

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

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

          if (errors?.length) {
            actions.push(
              of(
                setAction({
                  isLoading: false,
                }),
              ),
            );
          }

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

            if (processingComplete) {
              const MESSAGES = {
                [JOB_TYPE_THUMBNAIL_PROCESSING]: 'Thumbnail process successfully completed',
                [JOB_TYPE_THUMBNAILS_PUBLISHING]: 'Thumbnail successfully published',
              };

              const message = MESSAGES[processingJob];
              if (message) {
                actions.push(of(showNotificationAction({ type: TYPE_SUCCESS, message })));
              }

              if (processingJob === JOB_TYPE_THUMBNAILS_PUBLISHING) {
                actions.push(of(updateThumbnailInVideoListOrDetailAction()));
              }
            }
          }

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

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