package com.github.f1xman.movifier2.application.movie;

import com.github.f1xman.movifier2.application.shared.UseCase;
import com.github.f1xman.movifier2.domain.movie.ImdbId;
import com.github.f1xman.movifier2.domain.movie.Movie;
import com.github.f1xman.movifier2.domain.movie.MovieReference;
import com.github.f1xman.movifier2.domain.movie.MovieSource;

import static java.util.Objects.requireNonNull;

@UseCase
public class FollowUseCaseImpl implements FollowUseCase {

    private MovieRepository movieRepository;
    private MovieSource movieSource;

    public FollowUseCaseImpl(MovieRepository movieRepository, MovieSource movieSource) {
        this.movieRepository = requireNonNull(movieRepository);
        this.movieSource = requireNonNull(movieSource);
    }

    @Override
    public void follow(String imdbUrl, String userId) {
        ImdbId imdbId = ImdbId.parse(imdbUrl);
        MovieReference movieReference = new MovieReference(imdbId);
        Movie movie = movieReference
                .findOne(movieRepository)
                .orElseGet(() -> movieReference.fetchOne(movieSource));
        movie.follow(userId);
        movieRepository.save(movie);
    }
}
