package space.nstart.pcp.pcp_satellites_service.service

import org.slf4j.LoggerFactory
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.dao.DataAccessException
import org.springframework.stereotype.Component

@Component
class ComplexPlanRunStartupRecovery(
    private val complexPlanRunPersistenceService: ComplexPlanRunPersistenceService
) {

    private val logger = LoggerFactory.getLogger(this::class.java)

    @EventListener(ApplicationReadyEvent::class)
    fun onApplicationReady() {
        try {
            val recoveredRuns = complexPlanRunPersistenceService.markRunningRunsFailedOnStartup()
            if (recoveredRuns > 0) {
                logger.info("complexPlanRun startup recovery completed: recoveredRuns={}", recoveredRuns)
            }
        } catch (ex: DataAccessException) {
            logger.warn("complexPlanRun startup recovery skipped due to data access issue: {}", ex.message)
        }
    }
}
