package space.nstart.pcp.pcp_satellites_service.service

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

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

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

    @EventListener(ContextClosedEvent::class)
    fun onContextClosed() {
        try {
            val updatedRuns = complexPlanRunPersistenceService.markActiveRunsFailedOnShutdown()
            if (updatedRuns > 0) {
                logger.info("complexPlanRun shutdown handler completed: updatedRuns={}", updatedRuns)
            }
        } catch (ex: DataAccessException) {
            logger.warn("complexPlanRun shutdown handler skipped due to data access issue: {}", ex.message)
        }
    }
}
