package at.procon.ted.service;

import at.procon.ted.repository.ProcurementDocumentRepository;
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.OffsetDateTime;

/**
 * Service for cleaning up old procurement documents.
 *
 * Automatically deletes documents older than a configurable retention period.
 * Default: 7 years
 *
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DataCleanupService {

    private final ProcurementDocumentRepository documentRepository;

    @Value("${ted.cleanup.retention-years:7}")
    private int retentionYears;

    @Value("${ted.cleanup.enabled:false}")
    private boolean cleanupEnabled;

    /**
     * Delete procurement documents older than retention period.
     * Runs daily at 2 AM.
     */
    @Scheduled(cron = "${ted.cleanup.cron:0 0 2 * * *}")
    @Transactional
    public void deleteOldDocuments() {
        if (!cleanupEnabled) {
            log.debug("Data cleanup is disabled");
            return;
        }

        OffsetDateTime cutoffDate = OffsetDateTime.now().minusYears(retentionYears);

        log.info("Starting cleanup of documents older than {} (retention: {} years)",
                cutoffDate, retentionYears);

        try {
            int deletedCount = documentRepository.deleteByCreatedAtBefore(cutoffDate);

            if (deletedCount > 0) {
                log.info("✅ Deleted {} documents older than {} years", deletedCount, retentionYears);
            } else {
                log.debug("No documents to delete");
            }

        } catch (Exception e) {
            log.error("❌ Error during cleanup: {}", e.getMessage(), e);
        }
    }

    /**
     * Manually trigger cleanup of old documents.
     *
     * @param years Number of years to retain (documents older than this will be deleted)
     * @return Number of deleted documents
     */
    @Transactional
    public int deleteDocumentsOlderThan(int years) {
        OffsetDateTime cutoffDate = OffsetDateTime.now().minusYears(years);

        log.info("Manual cleanup: Deleting documents older than {} (retention: {} years)",
                cutoffDate, years);

        int deletedCount = documentRepository.deleteByCreatedAtBefore(cutoffDate);

        log.info("✅ Manually deleted {} documents", deletedCount);

        return deletedCount;
    }

    /**
     * Get count of documents that would be deleted.
     *
     * @param years Number of years to check
     * @return Number of documents older than specified years
     */
    public long countDocumentsOlderThan(int years) {
        OffsetDateTime cutoffDate = OffsetDateTime.now().minusYears(years);
        return documentRepository.countByCreatedAtBefore(cutoffDate);
    }
}
