package com.flowable.devops.config;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * Flowable 流程引擎配置
 * 
 * 关键配置说明：
 * 1. 禁用全局异步执行器，采用同步执行策略
 * 2. 审批节点（UserTask）自然暂停等待，审批完成后继续
 * 3. ServiceTask 统一使用 delegateExpression 指向 genericNodeExecutor
 */
@Configuration
public class FlowableConfig {

    /**
     * 配置事务管理器 - Flowable必需
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    
    /**
     * 配置 Flowable 流程引擎
     * 确保与 application.yml 中的配置保持一致
     */
    @Bean
    @Primary
    public SpringProcessEngineConfiguration processEngineConfiguration(
            DataSource dataSource, 
            PlatformTransactionManager transactionManager,
            Environment environment) {
        SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();
        
        // 数据源和事务管理器配置
        config.setDataSource(dataSource);
        config.setTransactionManager(transactionManager);
        
        // 数据库配置 - 根据环境自动设置
        String databaseSchemaUpdate = environment.getProperty("flowable.database-schema-update", "true");
        config.setDatabaseSchemaUpdate(databaseSchemaUpdate);
        
        // 统一使用MySQL数据库
        config.setDatabaseType("mysql");
        
        // 禁用异步执行器 - 关键配置！
        config.setAsyncExecutorActivate(false);
        
        // 历史记录级别
        config.setHistoryLevel(HistoryLevel.FULL);
        
        // 部署资源路径
        config.setDeploymentName("flowable-devops-processes");
        
        return config;
    }
}