package space.nstart.pcp.complan.service

import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException
import org.springframework.http.HttpStatus
import space.nstart.pcp.complan.db.repository.AplSettingsRepository
import space.nstart.pcp.complan.settings.AplSettings
import space.nstart.pcp.complan.settings.SettingsDTO

@Service
class AplSettingsLoader(
    private val aplSetRep: AplSettingsRepository,
    private val aplSettings: AplSettings,
    private val objectMapper: ObjectMapper
) {
    private val log = LoggerFactory.getLogger(this::class.java)

    @Transactional(readOnly = true)
    fun loadLatestSettings() {
        val settingsEntity = aplSetRep.findFirstByOrderByIdDesc()
        if (settingsEntity == null) {
            log.info("APL settings were not found in DB, current in-memory settings will be used")
            return
        }

        aplSettings.settings = try {
            objectMapper.readValue(settingsEntity.settings, SettingsDTO::class.java)
        } catch (error: Exception) {
            throw ResponseStatusException(
                HttpStatus.INTERNAL_SERVER_ERROR,
                "Failed to read APL settings from DB record id=${settingsEntity.id}",
                error
            )
        }
        log.info("APL settings loaded from DB record id={}", settingsEntity.id)
    }
}
