import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

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

import type { RootState } from '@/modules/@common/store/store';

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

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof updatePublishEntryAction> => action.type === 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$);
    }),
  );

export default epic;
