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.FileUploadSession;
import ru.soune.nocopy.entity.file.UploadStatus;
import ru.soune.nocopy.repository.FileUploadSessionRepository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class UploadSessionCleanupService {
    @Autowired
    private FileUploadSessionRepository fileUploadSessionRepository;

    @Autowired
    private FileUploadService fileUploadService;

    @Transactional
    @Scheduled(fixedDelay = 30000)
    public void cleanupSessions() {
        List<FileUploadSession> expiredSessions = fileUploadSessionRepository.findExpiredSessions(
                LocalDateTime.now(), Set.of(UploadStatus.INITIATED, UploadStatus.UPLOADING));

        for (FileUploadSession session : expiredSessions) {
            fileUploadService.handleExpiredSession(session);
        }
    }
}
