package com.honey.honey.service;

import com.honey.honey.repository.SessionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * Scheduled service for batch cleanup of expired sessions.
 * Runs every hour to delete expired sessions in batches to avoid long transactions.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SessionCleanupService {

    private final SessionRepository sessionRepository;
    
    @Value("${app.session.cleanup.batch-size:5000}")
    private int batchSize;
    
    @Value("${app.session.cleanup.max-batches-per-run:20}")
    private int maxBatchesPerRun;

    /**
     * Batch deletes expired sessions.
     * Runs every hour at minute 0.
     * Processes up to MAX_BATCHES_PER_RUN batches per run.
     */
    @Scheduled(cron = "0 0 * * * ?") // Every hour at minute 0
    @Transactional
    public void cleanupExpiredSessions() {
        LocalDateTime now = LocalDateTime.now();
        int totalDeleted = 0;
        int batchesProcessed = 0;
        
        log.info("Starting expired session cleanup (batchSize={}, maxBatches={})", batchSize, maxBatchesPerRun);
        
        while (batchesProcessed < maxBatchesPerRun) {
            int deleted = sessionRepository.deleteExpiredSessionsBatch(now, batchSize);
            totalDeleted += deleted;
            batchesProcessed++;
            
            // If we deleted less than batch size, we've caught up
            if (deleted < batchSize) {
                break;
            }
        }
        
        if (totalDeleted > 0) {
            log.info("Session cleanup completed: deleted {} expired session(s) in {} batch(es)", 
                    totalDeleted, batchesProcessed);
        } else {
            log.debug("Session cleanup completed: no expired sessions found");
        }
    }
}

