package app.config;

import jakarta.persistence.EntityManagerFactory;
import java.util.Properties;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableTransactionManagement
public class EntityManagerConfiguration {
  
    //@Value( "${hibernateDialect}" )
    private String hibernateDialect = "org.hibernate.dialect.MySQLDialect";
  
    //@Value( "${hibernateShowSql}" )
    boolean hibernateShowSql = true;

    //@Value( "${jpaGenerateDdl}" )
    boolean jpaGenerateDdl = false;
  
    final Properties additionalProperties(){
        return new Properties(){
            {// use this to inject additional properties in the EntityManager
                setProperty("useSecondLevelCache", "org.hibernate.cache.RegionFactory");
                setProperty("useQueryCache", "org.hibernate.cache.RegionFactory");
            }
        };
    }
    
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManager(DataSource dataSource){
        final LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource( dataSource );
        entityManager.setPackagesToScan(new String[] {
                "app.model"
                }); 
        final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(){
            {
                setDatabase( Database.MYSQL );
                setDatabasePlatform( hibernateDialect );
                setShowSql( hibernateShowSql );
                setGenerateDdl( jpaGenerateDdl );
            }
        };
        entityManager.setJpaVendorAdapter( vendorAdapter );
        entityManager.setJpaProperties( additionalProperties() );
        return entityManager;
    }    
    
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }

}
