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

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

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

const queryGQL = `
  mutation AiWorkbenchPublishUnpublishDescriptionQuery(
    $videoId: String!,
    $publish: Boolean!,
  ) {
    aiWorkbenchPublishUnpublishDescription(
      videoId: $videoId,
      publish: $publish,
    ) {
      published
      draft
      processing
    }
  }
`;

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

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

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

            actions.push(
              of(setAction(payload)),
              of(updateDescriptionInVideoListOrDetailAction(action.payload)),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: action.payload
                    ? 'Description successfully published!'
                    : 'Description successfully unpublished!',
                }),
              ),
            );
          }

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

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