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

import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;

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

import jakarta.annotation.security.PermitAll;
import jakarta.ejb.Stateless;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;

/**
 * 
 * 
 * <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: 19 Jan 2026
 */
@Stateless
@SuppressWarnings("unchecked")
@PermitAll
public class QueryService {
	private static final Log LOG = LogFactory.getLog(QueryService.class);

	@PersistenceContext
	private EntityManager eManager;

	public <T> Optional<T> callNamedQuerySingleResult(String namedQuery, Param... params) {
		return singleResult(eManager.createNamedQuery(namedQuery), Arrays.asList(params));
	}

	private <T> Optional<T> singleResult(Query query, Collection<Param> params) {
		try {
			for (Param param : params) {
				query.setParameter(param.name(), param.value());
			}
			return Optional.ofNullable((T) query.getSingleResult());
		} catch (NoResultException nre) {
			LOG.debug("No entity found for query " + query + " with params " + params);
			LOG.trace("NoResultException", nre);
			return Optional.empty();
		}
	}

	public <T> T callNamedQueryList(String namedQuery, Param... objects) {
		Query query = eManager.createNamedQuery(namedQuery);
		for (Param param : objects) {
			query.setParameter(param.name(), param.value());
		}
		return (T) query.getResultList();
	}

	public int callNamedQueryUpdate(String namedQuery, Param... objects) {
		Query query = eManager.createNamedQuery(namedQuery);
		for (Param param : objects) {
			query.setParameter(param.name(), param.value());
		}
		return query.executeUpdate();
	}
}
