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

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

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

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

const queryGQL = `
  mutation ${SET_AIW_THUMBNAIL_DRAFT}($payload: ${SET_AIW_THUMBNAIL_DRAFT_PAYLOAD}) {
    ${SET_AIW_THUMBNAIL_DRAFT}(payload: $payload) {
      published
      draft
      draftPreview {
        uid
        url
      }
      thumbnailOptions {
        uid
        url
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          // payload object
          // uid ( when selected options ) or thumbnail ( when upload )
          payload: {
            videoId: video.uid,
            ...action.payload,
          },
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data[SET_AIW_THUMBNAIL_DRAFT];
          const payload = { isLoading: false };

          if (!errors?.length) {
            payload.thumbnailDraftPreview = response.draftPreview;
            payload.thumbnailOptions = response?.thumbnailOptions ?? [];
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.isDirty = true;
          }

          return concat(of(setAction(payload)));
        }),
      );

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