package de.thpeetz.kontor.infrastructure;

import java.util.Objects;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AppHibernateSessionFactory {

    private static final Logger logger = LoggerFactory.getLogger(AppHibernateSessionFactory.class);

    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (Objects.isNull(sessionFactory)) {
            var configuration = AppHibernateConfig.configuration();
            final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .build();
            try {
                sessionFactory = configuration.buildSessionFactory(registry);
                logger.info("SessionFactory created");
            } catch (Throwable ex) {
                logger.error("Failed to create session factory", ex);
                StandardServiceRegistryBuilder.destroy(registry);
            }
        }
        return sessionFactory;
    }
}
