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

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

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

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

const queryGQL = `
  mutation ${PUBLISH_AIW_THUMBNAIL}($payload: ${PUBLISH_AIW_THUMBNAIL_PAYLOAD}) {
    ${PUBLISH_AIW_THUMBNAIL}(payload: $payload) {
      published
      draft
      processing
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          payload: {
            videoId: video.uid,
            publish: action.payload,
          },
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data[PUBLISH_AIW_THUMBNAIL];
          const payload = { isLoading: false };
          const actions = [];

          if (!errors?.length) {
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.isDirty = false;

            actions.push(of(setAction(payload)), of(monitoringStartAction()));
          }

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

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