package com.crm.rely.backend.configuration;

import com.crm.rely.backend.aspect.EntityScanPathResolver;
import com.crm.rely.backend.aspect.HibernateQueryInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private EntityScanPathResolver entityScanPathResolver;

    @Autowired
    private HibernateQueryInterceptor queryInterceptor;

    @Value("${spring.jpa.hibernate.interceptor.enableDeleteCondition:false}")
    private boolean enableDeleteCondition;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        Map<String, Object> jpaProperties = new HashMap<>();
        if (!enableDeleteCondition) {
            jpaProperties.put("hibernate.ejb.interceptor", queryInterceptor);
        }
        jpaProperties.put("hibernate.show_sql", true);
        jpaProperties.put("hibernate.format_sql", true);
        // 使用自定义的命名策略
        jpaProperties.put("hibernate.physical_naming_strategy",
                "com.crm.rely.backend.util.SnakeCasePhysicalNamingStrategy");

        return builder
                .dataSource(dataSource)
                .packages(entityScanPathResolver.getEntityScanPaths())
                .persistenceUnit("default") // 自定义持久化单元
                .properties(jpaProperties)
                .build();
    }

}