class MovieIndexHelper {

    public void indexMovie(final Movie movie) {
        try {
            // Deletes the movie if it's indicated as deleted
            if (movie.isDeleted()) {
                movieIndexRepository.deleteById(movie.getId());
                movieLikeRepository.deleteByMovieId(movie.getId());
                movieRepository.deleteById(movie.getId());

                return;
            }

            // Saves the pending likes
            movie.getPendingLikes().forEach(account -> {
                final MovieLike movieLike = new MovieLike();
                movieLike.setId(movie.getId() + "-" + account);
                movieLike.setMovieId(movie.getId());
                movieLike.setAccount(account);

                movieLikeRepository.save(movieLike);
            });
            movie.setPendingLikes(new HashSet<>());

            // Removes the pending unlikes
            movie.getPendingUnlikes()
                .forEach(account -> movieLikeRepository.deleteById(movie.getId() + "-" + account));
            movie.setPendingUnlikes(new HashSet<>());

            // Calculates the total likes
            movie.setTotalLikes(movieLikeRepository.countByMovieId(movie.getId()));

            // Indexes the movie
            final MovieIndex movieIndex = movieMapper.movieToMovieIndex(movie);
            movieIndexRepository.save(movieIndex);

            // Updates the movie in the database
            final String currentRevision = movie.getRevision();
            movie.setRevision(UUID.randomUUID().toString());
            movie.setUpdated(false);
            movieRepository.updateMovie(movie, currentRevision);
        }
        catch (final Exception ex) {
            log.error(String.format("An error occured while indexing movie %s: %s", movie.getId(), ex.getMessage()),
                ex);
        }
    }

}