package de.oaa.xxx.user;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import jakarta.transaction.UserTransaction;

@ApplicationScoped
public class UserDAO {

	private Logger LOGGER = LoggerFactory.getLogger(getClass());

	@PersistenceContext(name = "user")
	private EntityManager entityManager;
	@Resource
	private UserTransaction transaction;

	public void update(UserEntity toUpdate) {
		try {
			transaction.begin();
			entityManager.merge(toUpdate);
			transaction.commit();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
		}
	}

	public void persist(UserEntity toPersist) {
		try {
			transaction.begin();
			LOGGER.info("Persisting Entity " + toPersist);
			entityManager.persist(toPersist);
			transaction.commit();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
		}
	}

	public void remove(UserEntity toRemove) {
		try {
			transaction.begin();
			entityManager.remove(toRemove);
			transaction.commit();
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
		}
	}
	
	public UserEntity findById(UUID id) {
		return entityManager.find(UserEntity.class, id);
	}
	
	public UserEntity login(String email, String password) {
		try {
			transaction.begin();
			TypedQuery<UserEntity> query = entityManager.createQuery("select u from UserEntity u where u.email = :email and u.password = :password", UserEntity.class);
			query.setParameter("email", email);
			query.setParameter("password", password);
			UserEntity result = query.getSingleResult();
			transaction.commit();
			return result;
		} catch (Exception exception) {
			LOGGER.error(exception.getMessage(), exception);
			return null;
		}
	}
}