package com.rj.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import lombok.extern.slf4j.Slf4j;

/**
 * SQL性能监控配置
 * 
 * @author 李中华
 * @since 2025-08-08
 */
@Slf4j
@Configuration
public class SqlPerformanceConfig {

    /**
     * SQL执行时间监控
     */
    @Bean
    @Profile({"dev", "test"})
    public SqlPerformanceInterceptor sqlPerformanceInterceptor() {
        return new SqlPerformanceInterceptor();
    }

    /**
     * SQL性能监控拦截器
     */
    public static class SqlPerformanceInterceptor {
        
        private static final long SLOW_SQL_THRESHOLD = 1000; // 1秒
        
        public void beforeExecute(String sql, Object[] params) {
            log.info("=== SQL执行开始 ===");
            log.info("SQL: {}", sql);
            if (params != null && params.length > 0) {
                log.info("参数: {}", java.util.Arrays.toString(params));
            }
        }
        
        public void afterExecute(String sql, long executionTime) {
            log.info("SQL执行完成，耗时: {}ms", executionTime);
            if (executionTime > SLOW_SQL_THRESHOLD) {
                log.warn("⚠️ 慢SQL警告: 执行时间 {}ms 超过阈值 {}ms", executionTime, SLOW_SQL_THRESHOLD);
            }
            log.info("=== SQL执行结束 ===\n");
        }
        
        public void onError(String sql, Exception e) {
            log.error("SQL执行异常: {}", sql, e);
        }
    }
} 