package ru.soune.nocopy.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.repository.FileEntityRepository;
import ru.soune.nocopy.service.file.ImageResizeService;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Component
@Slf4j
public class ImageMigration {

    @Autowired
    private FileEntityRepository fileRepository;

    @Autowired
    private ImageResizeService imageResizeService;

    @EventListener(ApplicationReadyEvent.class)
    public void migrate() {
        List<FileEntity> images = fileRepository.findByThumbnailPathIsNull();

        for (FileEntity file : images) {
            try {
                Path path = Paths.get(file.getProtectedFilePath());
                if (Files.exists(path)) {
                    byte[] data = Files.readAllBytes(path);
                    imageResizeService.generateSizes(file, data);
                    fileRepository.save(file);
                }
            } catch (Exception e) {
                log.error("Error migrating {}: {}", file.getId(), e.getMessage());
            }
        }
    }
}
