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

import { getPublishEntriesAction, updatePublishEntryAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation videoUpdatePublishEntry(
    $id: String!,
    $videoId: String!,
    $settings: [VideoPublishEntrySettingsInputType],
    $viewability: String,
    $postText: String!,
    ) {
      videoUpdatePublishEntry(
      id: $id,
      videoId: $videoId,
      settings: $settings,
      viewability: $viewability,
      postText: $postText,
      ) {
        id
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(updatePublishEntryAction.type),
    switchMap((action) => {
      const { videoId, postText, ...info } = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId,
          postText: postText || '',
          ...info,
        },
      }).pipe(switchMap(() => concat(of(getPublishEntriesAction(videoId)))));

      return concat(stream$);
    }),
  );
