package com.cos.service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.logging.Logger;

/**
 * Singleton EntityManagerFactory holder for plain Tomcat (non-JEE) deployment.
 * Provides thread-safe EntityManager creation without requiring a full JEE container.
 */
public class EntityManagerProducer {

    private static final Logger LOGGER = Logger.getLogger(EntityManagerProducer.class.getName());
    private static EntityManagerFactory emf;

    static {
        try {
            emf = Persistence.createEntityManagerFactory("cosPU");
            LOGGER.info("EntityManagerFactory initialized successfully for persistence unit: cosPU");
        } catch (Exception e) {
            LOGGER.severe("Failed to initialize EntityManagerFactory: " + e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * Create a new EntityManager instance.
     * Caller is responsible for closing it.
     */
    public static EntityManager createEntityManager() {
        return emf.createEntityManager();
    }

    /**
     * Get the shared EntityManagerFactory.
     */
    public static EntityManagerFactory getEntityManagerFactory() {
        return emf;
    }

    /**
     * Close the factory on application shutdown.
     */
    public static void closeFactory() {
        if (emf != null && emf.isOpen()) {
            emf.close();
            LOGGER.info("EntityManagerFactory closed.");
        }
    }

    private EntityManagerProducer() {}
}