package cn.reghao.oss.store.db.repository;

import cn.reghao.oss.store.api.dto.media.VideoInfo;
import cn.reghao.oss.store.api.dto.media.VideoUrlDto;
import cn.reghao.oss.store.db.mapper.VideoFileMapper;
import cn.reghao.oss.store.model.po.VideoFile;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2023-08-28 15:00:43
 */
@Repository
public class VideoRepository {
    private final VideoFileMapper videoFileMapper;

    public VideoRepository(VideoFileMapper videoFileMapper) {
        this.videoFileMapper = videoFileMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveVideoFiles(List<VideoFile> videoFiles) {
        videoFileMapper.saveAll(videoFiles);
    }

    public List<String> deleteVideoFile(String videoFileId) {
        List<String> objectIds = videoFileMapper.findByVideoFileId(videoFileId).stream()
                .map(VideoFile::getObjectId)
                .collect(Collectors.toList());
        deleteVideoFile0(videoFileId);
        return objectIds;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteVideoFile0(String videoFileId) {
        videoFileMapper.deleteByVideoFileId(videoFileId);
    }

    public List<VideoInfo> getVideoInfos(String videoFileId) {
        return videoFileMapper.findVideoInfo(videoFileId);
    }

    public VideoFile getOriginalVideoFile(String videoFileId) {
        List<VideoFile> list = videoFileMapper.findByVideoFileId(videoFileId);
        return list.isEmpty() ? null : list.get(0);
    }

    public List<VideoFile> getVideoFiles(String videoFileId) {
        List<VideoFile> list = videoFileMapper.findByVideoFileId(videoFileId);
        return list;
    }

    //@Cacheable(cacheNames = "oss:store:videoUrls", key = "#videoFileId", unless = "#result.empty")
    public List<VideoUrlDto> findVideoUrls(String videoFileId) {
        return videoFileMapper.findVideoUrls(videoFileId);
    }
}
