SettingsService.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package org.archtool.service

import org.archtool.data.entity.SettingsEntity
import org.archtool.data.model.UpdateStatus
import org.archtool.repository.SettingsRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant
import java.util.UUID

@Service
class SettingsService(
    private val settingsRepository: SettingsRepository
) {
    @Transactional
    suspend fun getSettingValue(key: String): String? {
        val entity = settingsRepository.findByName(key)
        return entity?.value
    }

    @Transactional
    suspend fun setSettingValue(key: String, value: String, expirationTime: Instant? = null) {
        val existingEntity = settingsRepository.findByName(key)

        if (existingEntity != null) {
            val updatedEntity = existingEntity.copy(
                value = value,
                lastUpdateTime = Instant.now(),
                expirationTime = expirationTime
            )
            settingsRepository.save(updatedEntity)
        } else {
            val newEntity = SettingsEntity(
                settingId = UUID.randomUUID(),
                name = key,
                value = value,
                creationTime = Instant.now(),
                lastUpdateTime = Instant.now(),
                expirationTime = expirationTime,
                new = true
            )
            settingsRepository.save(newEntity)
        }
    }

    // UpdateSequence methods
    @Transactional
    suspend fun incrementUpdateSequence(): Long {
        return settingsRepository.upsertAndIncrementSequence(
            settingId = UUID.randomUUID(),
            name = SETTINGS_KEY_UPDATE_SEQUENCE,
            value = "0",
            creationTime = Instant.now(),
            lastUpdateTime = Instant.now(),
            expirationTime = null
        )
    }

    // Lock methods - using atomic insert
    @Transactional
    suspend fun tryLock(key: String, value: UUID, expirationTime: Instant? = null): Boolean {
        val result = settingsRepository.insertIfNotExists(
            settingId = value,
            name = key,
            value = value.toString(),
            creationTime = Instant.now(),
            lastUpdateTime = Instant.now(),
            expirationTime = expirationTime
        )
        // Возвращаем true, если вставка удалась (ключ был добавлен), false - если уже существовал
        return result > 0
    }

    @Transactional
    suspend fun unlock(key: String, value: UUID): Boolean {
        val entity = settingsRepository.findByName(key)
        return if (entity != null && UUID.fromString(entity.value) == value) {
            settingsRepository.delete(entity)
            true
        } else {
            false
        }
    }

    // ActiveSequence methods
    @Transactional
    suspend fun getActiveSequence(): Long? =
        getSettingValue(SETTINGS_KEY_ACTIVE_SEQUENCE)?.toLong()

    @Transactional
    suspend fun setActiveSequence(value: Long, expirationTime: Instant? = null) =
        setSettingValue(SETTINGS_KEY_ACTIVE_SEQUENCE, value.toString(), expirationTime)

    // UpdateStatus methods
    @Transactional
    suspend fun getUpdateStatus(): UpdateStatus? {
        val raw = getSettingValue(SETTINGS_KEY_UPDATE_STATUS)
        return raw?.let { UpdateStatus.valueOf(it) }
    }

    @Transactional
    suspend fun setUpdateStatus(status: UpdateStatus, expirationTime: Instant? = null) =
        setSettingValue(SETTINGS_KEY_UPDATE_STATUS, status.name, expirationTime)

    // UpdateCompletionTime methods
    @Transactional
    suspend fun getUpdateCompletionTime(): Instant? {
        val raw = getSettingValue(SETTINGS_KEY_UPDATE_COMPLETION_TIME)
        return raw?.let { Instant.parse(it) }
    }

    @Transactional
    suspend fun setUpdateCompletionTime(time: Instant) =
        setSettingValue(SETTINGS_KEY_UPDATE_COMPLETION_TIME, time.toString())

    // UpdateErrorMessage methods
    @Transactional
    suspend fun getUpdateErrorMessage(): String? =
        getSettingValue(SETTINGS_KEY_UPDATE_ERROR_MESSAGE)

    @Transactional
    suspend fun setUpdateErrorMessage(message: String) =
        setSettingValue(SETTINGS_KEY_UPDATE_ERROR_MESSAGE, message)

    @Transactional
    suspend fun deleteUpdateErrorMessage() {
        val entity = settingsRepository.findByName(SETTINGS_KEY_UPDATE_ERROR_MESSAGE)
        if (entity != null) {
            settingsRepository.delete(entity)
        }
    }

    companion object {
        const val SETTINGS_KEY_UPDATE_SEQUENCE = "vcs-adapter:update-sequence"
        const val SETTINGS_KEY_ACTIVE_SEQUENCE = "vcs-adapter:active-sequence"
        const val SETTINGS_KEY_UPDATE_STATUS = "vcs-adapter:update-status"
        const val SETTINGS_KEY_UPDATE_ERROR_MESSAGE = "vcs-adapter:update-error-message"
        const val SETTINGS_KEY_UPDATE_COMPLETION_TIME = "vcs-adapter:update-completion-time"
    }
}