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

import { MODE_LIST } from '../../../../common/constants';

import { modeSelector, playlistsSelector } from '../../selectors';
import { deletePlaylistAction, setModeAction, setPlaylistsAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';
import { deleteLiveEventPlaylistAction } from '@/modules/liveEvents/liveEvent/redux/slices';

const queryGQL = `
  mutation deletePlaylist(
    $id: Int!,
    $publisherId: Int!
  ) {
    deletePlaylist(
      id: $id,
      publisherId: $publisherId
    ) {
      playlistId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(deletePlaylistAction.type, deleteLiveEventPlaylistAction.type),
    filter((action) => action.payload.publisherId),
    switchMap((action) => {
      const { id, publisherId } = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id,
          publisherId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const mode = modeSelector(state$.value);
            const playlists = playlistsSelector(state$.value);

            const newPlaylists = playlists.filter((playlist) => playlist.id !== data.deletePlaylist.playlistId);

            actions.push(of(setPlaylistsAction(newPlaylists)));
            actions.push(of(setPlaylistsAction(newPlaylists)));

            if (mode !== MODE_LIST) {
              actions.push(of(setModeAction(MODE_LIST)));
            }
          }

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

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