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

import { QUERY_PARAM_PLAYLIST } from '@/modules/editorial/constants/routing';

import { getPlaylistByIdAction } from '../../../redux/slices';
import { clearCreateFormAction, duplicatePlaylistAction, setIsLoadingAction } from '../slices';
import { removeQueriesAction } from '@/modules/@common/location/redux/slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import {
  duplicatedPlaylistIdSelector,
  nameSelector,
  playerSelector,
  urlSelector,
} from '@/modules/editorial/RightSideBar/TabPlaylist/Edit/redux/selectors';

const queryGQL = `
  mutation duplicatePlaylist(
    $playlistId: Int!,
    $name: String!,
    $playerId: Int!,
    $url: String,
  ) {
    duplicatePlaylist(
      playListId: $playlistId,
      name: $name,
      url: $url,
      playerId: $playerId
    ) {
      playlistId
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(duplicatePlaylistAction.type),
    filter(() => !!getToken()),
    switchMap(() => {
      const duplicatedPlaylistId = duplicatedPlaylistIdSelector(state$.value);
      const name = nameSelector(state$.value);
      const url = urlSelector(state$.value);
      const playerId = playerSelector(state$.value).id;

      const params = {
        playlistId: duplicatedPlaylistId,
        name,
        playerId,
      };
      if (url) {
        params.url = url;
      }

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

          if (!errors.length) {
            actions.push(
              of(clearCreateFormAction()),
              of(removeQueriesAction([QUERY_PARAM_PLAYLIST])),
              of(getPlaylistByIdAction({ id: data.duplicatePlaylist.playlistId })),
            );
          }

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

      return concat(of(setIsLoadingAction(true)), stream$, of(setIsLoadingAction(false)));
    }),
  );
