package ru.soune.nocopy.service.file;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.file.FileStatus;
import ru.soune.nocopy.repository.FileEntityRepository;

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

@Service
@RequiredArgsConstructor
public class NotExistFilesCleanupService {

    @Autowired
    private FileEntityRepository fileEntityRepository;

    @Transactional
    @Scheduled(fixedDelay = 30000)
    public void cleanUpNotExistFiles() {
        List<FileEntity> fileEntities = fileEntityRepository.searchFileEntityByStatus(FileStatus.DELETED);

        for (FileEntity fileEntity : fileEntities) {
            boolean exists = Files.exists(Paths.get(fileEntity.getFilePath()));
            if (!exists) {
                fileEntityRepository.delete(fileEntity);
            }
        }
    }
}
