package com.ffii.fpsms.modules.monitoring.service

import com.ffii.core.support.JdbcDao
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime

@Service
open class MonitoringRetentionService(
    private val jdbcDao: JdbcDao,
    private val clientPresenceService: ClientPresenceService,
) {
    private val log = LoggerFactory.getLogger(MonitoringRetentionService::class.java)

    @Value("\${fpsms.monitoring.event-retention-days:30}")
    private var retentionDays: Long = 30

    @Transactional
    open fun purgeOldEvents(): Map<String, Int> {
        val days = retentionDays.coerceAtLeast(1)
        val cutoff = LocalDateTime.now().minusDays(days)

        val deviceDeleted = jdbcDao.executeUpdate(
            """
                DELETE FROM client_presence_event
                WHERE recorded_at < :cutoff
            """.trimIndent(),
            mapOf("cutoff" to cutoff),
        )
        val printerDeleted = jdbcDao.executeUpdate(
            """
                DELETE FROM printer_connectivity_event
                WHERE recorded_at < :cutoff
            """.trimIndent(),
            mapOf("cutoff" to cutoff),
        )

        val stalePresenceDeleted = clientPresenceService.purgeStalePresence()

        if (deviceDeleted > 0 || printerDeleted > 0 || stalePresenceDeleted > 0) {
            log.info(
                "Monitoring retention: deleted {} device event(s), {} printer event(s) older than {} day(s) (before {}), and {} stale presence row(s)",
                deviceDeleted,
                printerDeleted,
                days,
                cutoff,
                stalePresenceDeleted,
            )
        }

        return mapOf(
            "deviceEventsDeleted" to deviceDeleted,
            "printerEventsDeleted" to printerDeleted,
            "stalePresenceDeleted" to stalePresenceDeleted,
            "retentionDays" to days.toInt(),
        )
    }
}
