package io.delphiplatform.api.v3.rdb.repository;

import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Set;

import io.delphiplatform.api.v3.rdb.entity.video.VideoEntity;

public interface VideoRepository extends JpaRepository<VideoEntity, String>, JpaSpecificationExecutor<VideoEntity> {

    @Query(nativeQuery = true,
        value = ""
            + "with isrcs as (  "
            + "       select distinct on (t.isrc) t.isrc "
            + "           from track t "
            + "                    inner join artist_track at on t.track_id = at.track_id "
            + "           where at.artist_id in :artist_ids ) "
            + "   select distinct on (vi.video_id) vi.video_id "
            + "       from video_isrc vi "
            + "       where vi.isrc in ( select isrc from isrcs ) "
            + "       and vi.content_type = :content_type "
            + "       and vi.views > :min_views")
    Set<String> findVideoIdsWithArtistIdAndContentType(@Param("artist_ids") Set<String> artistIds,
        @Param("content_type") String contentType, @Param("min_views") Long minViews);

    @EntityGraph(attributePaths = "isrcs")
    List<VideoEntity> findByVideoIdIn(Set<String> videoIds);

    boolean existsByVideoIdIn(Set<String> videoIds);

}
