package org.nstart.dep265.requestservice.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionDefinition
import org.springframework.transaction.support.TransactionOperations
import org.springframework.transaction.support.TransactionTemplate

@Configuration
class OutboxTransactionConfig {
    @Bean("routeMatchingTransactionOperations")
    fun routeMatchingTransactionOperations(transactionManager: PlatformTransactionManager): TransactionOperations {
        return TransactionTemplate(transactionManager).apply {
            propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRED
        }
    }

    @Bean("outboxTransactionOperations")
    fun outboxTransactionOperations(transactionManager: PlatformTransactionManager): TransactionOperations {
        return TransactionTemplate(transactionManager).apply {
            propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW
        }
    }

    /**
     * Каждый батч планировщика истечения коммитится отдельно, поэтому между батчами
     * row-level блокировки (FOR UPDATE SKIP LOCKED) освобождаются.
     */
    @Bean("requestExpiryTransactionOperations")
    fun requestExpiryTransactionOperations(transactionManager: PlatformTransactionManager): TransactionOperations {
        return TransactionTemplate(transactionManager).apply {
            propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW
        }
    }
}
