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

import { deleteAiPlaylistAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { configChangedEventAction } from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';

const queryGQL = `
  mutation deleteAiPlaylist(
    $watchId: Int!,
    $channelId: Int!,
    $aiPlaylistId: Int!,
  ) {
    deleteAiPlaylist(
      watchId: $watchId,
      channelId: $channelId,
      aiPlaylistId: $aiPlaylistId,
    ) {
      id
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(deleteAiPlaylistAction.type),
    switchMap(({ payload: { watchId, channelId, aiPlaylistId } }) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          watchId,
          channelId,
          aiPlaylistId,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(configChangedEventAction()));
          }

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

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