package com.ffii.fpsms.modules.monitoring.scheduler

import com.ffii.fpsms.modules.monitoring.service.PrinterMonitorService
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component

@Component
@ConditionalOnProperty(prefix = "fpsms.monitoring", name = ["enabled"], havingValue = "true")
class PrinterMonitorScheduler(
    private val printerMonitorService: PrinterMonitorService,
) {
    private val log = LoggerFactory.getLogger(PrinterMonitorScheduler::class.java)

    @Scheduled(fixedRateString = "\${fpsms.printer-monitor.scan-interval-ms:120000}")
    fun scanPrinters() {
        try {
            val result = printerMonitorService.checkAllPrinters()
            @Suppress("UNCHECKED_CAST")
            val summary = result["summary"] as? Map<String, Any>
            val offline = summary?.get("offline") ?: 0
            if ((offline as? Number)?.toInt()?.let { it > 0 } == true) {
                log.warn("Printer monitor: {} printer(s) offline", offline)
            }
        } catch (e: Exception) {
            log.error("Printer connectivity scan failed", e)
        }
    }
}
