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 deleteEditorialAiPlaylist(
    $editorialPlaylistId: Int!,
    $aiPlaylistId: Int!,
  ) {
    deleteEditorialAiPlaylist(
      editorialPlaylistId: $editorialPlaylistId,
      aiPlaylistId: $aiPlaylistId,
    )
  }
`;

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

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

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

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