package com.test.bijihoudaun.service;

import com.test.bijihoudaun.util.MarkdownImageExtractor;
import com.test.bijihoudaun.mapper.ImageMapper;
import com.test.bijihoudaun.mapper.MarkdownFileMapper;
import com.test.bijihoudaun.mapper.ImageNameMapper;
import com.test.bijihoudaun.entity.Image;
import com.test.bijihoudaun.entity.MarkdownFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 图片清理服务类
 * 用于清理不再被笔记引用的冗余图片
 */
@Service
public class ImageCleanupService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private MarkdownFileMapper markdownFileMapper;

    @Autowired
    private ImageNameMapper imageNameMapper;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 清理冗余图片
     * @return 清理的图片数量
     */
    @Transactional
    public int cleanupRedundantImages() {
        // 批量获取所有笔记的ID和content（避免N+1查询）
        List<MarkdownFile> allMarkdownFiles = markdownFileMapper.selectAllIdsAndContent();

        // 用于存储所有被引用的图片文件名
        Set<String> referencedImageNames = new HashSet<>();

        // 遍历所有笔记，收集被引用的图片
        for (MarkdownFile markdownFile : allMarkdownFiles) {
            String content = (markdownFile != null) ? markdownFile.getContent() : "";
            List<String> imageNames = MarkdownImageExtractor.extractImageFilenames(content);
            referencedImageNames.addAll(imageNames);
        }

        // 获取所有图片记录
        List<Image> allImages = imageMapper.findAll();

        // 记录被删除的图片数量
        int deletedCount = 0;

        // 遍历所有图片，删除未被引用的
        for (Image image : allImages) {
            if (!referencedImageNames.contains(image.getStoredName())) {
                // 删除物理文件
                fileStorageService.deleteFile(image.getStoredName());

                // 删除数据库记录
                imageMapper.deleteById(image.getId());

                // 如果存在image_name表中的记录，也一并删除
                imageNameMapper.deleteByFileName(image.getStoredName());

                deletedCount++;
            }
        }

        return deletedCount;
    }
}
