package marketing.heyday.hartmann.fotodocumentation.core.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jakarta.annotation.Resource;
import jakarta.ejb.EJB;
import jakarta.ejb.EJBContext;
import jakarta.ejb.SessionContext;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import marketing.heyday.hartmann.fotodocumentation.core.query.QueryService;
import marketing.heyday.hartmann.fotodocumentation.core.utils.StorageUtils.StorageState;

/**
 * 
 * <p>Copyright: Copyright (c) 2024</p>
 * <p>Company: heyday Marketing GmbH</p>
 * @author <a href="mailto:p.verboom@heyday.marketing">Patrick Verboom</a>
 * @version 1.0
 * 
 * created: 21 Jan 2026
 */

public abstract class AbstractService {
	private static final Log LOG = LogFactory.getLog(AbstractService.class);
	
	@Resource
	protected EJBContext ejbContext;

	@PersistenceContext
	protected EntityManager entityManager;

	@Resource
	protected SessionContext sessionContext;

	@EJB
	protected QueryService queryService;
	
	protected <T> StorageState delete(Class<T> type, Long id) {
		try {
			T entity = entityManager.getReference(type, id);
			entityManager.remove(entity);
			entityManager.flush();
			return StorageState.OK;
		} catch (EntityNotFoundException e) {
			LOG.warn("Failed to delete entity " + type + " not found " + id, e);
			ejbContext.setRollbackOnly();
			return StorageState.NOT_FOUND;
		}
	}
}
