package com.ecep.contract.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;

import org.hibernate.Hibernate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.repository.CrudRepository;

import com.ecep.contract.SpringApp;

public class HibernateUtils {
    /**
     * @param bean
     * @param repositoryClass
     * @param <T>
     * @param <ID>
     * @return
     */
    public static <T, ID> T initialize(
            T bean,
            Class<? extends CrudRepository<T, ID>> repositoryClass
    ) {
        if (Hibernate.isInitialized(bean)) {
            return bean;
        }
        PropertyDescriptor idDescriptor = BeanUtils.getPropertyDescriptor(bean.getClass(), "id");
        if (idDescriptor != null) {
            try {
                ID id = (ID) idDescriptor.getReadMethod().invoke(bean);
                return SpringApp.getBean(repositoryClass).findById(id).orElse(bean);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        return bean;
    }

}
