package com.ffii.fpsms.modules.jobOrder.scheduler

import com.ffii.fpsms.modules.jobOrder.service.LaserBag2AutoSendService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDate

/**
 * Periodically runs the same laser TCP send as /laserPrint (DB LASER_PRINT.host / port / itemCodes).
 * Disabled by default; set laser.bag2.auto-send.enabled=true.
 */
@Component
class LaserBag2AutoSendScheduler(
    private val laserBag2AutoSendService: LaserBag2AutoSendService,
    @Value("\${laser.bag2.auto-send.enabled:false}") private val enabled: Boolean,
    @Value("\${laser.bag2.auto-send.limit-per-run:1}") private val limitPerRun: Int,
) {
    private val logger = LoggerFactory.getLogger(javaClass)

    @Scheduled(fixedRateString = "\${laser.bag2.auto-send.interval-ms:60000}")
    fun tick() {
        if (!enabled) {
            return
        }
        try {
            val report = laserBag2AutoSendService.runAutoSend(
                planStart = LocalDate.now(),
                limitPerRun = limitPerRun,
            )
            logger.info(
                "Laser Bag2 scheduler: processed {}/{} job orders for {}",
                report.jobOrdersProcessed,
                report.jobOrdersFound,
                report.planStart,
            )
        } catch (e: Exception) {
            logger.error("Laser Bag2 scheduler failed", e)
        }
    }
}
