package com.eshore.gringotts.web.helper;

import cn.hutool.core.util.ObjectUtil;
import com.eshore.gringotts.web.domain.base.entity.SimpleEntity;
import com.eshore.gringotts.web.domain.user.entity.User;
import com.eshore.gringotts.web.domain.user.service.UserService;
import java.util.function.Supplier;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * JPA工具
 *
 * @author lanyuanxiaoyao
 * @date 2024-11-25
 */
public class EntityHelper {
    public static <E, ID> void deleteIfUpdateNeeded(JpaRepository<E, ID> repository, Supplier<E> getter, E target) {
        E old = getter.get();
        if (ObjectUtil.notEqual(old, target)) {
            repository.delete(old);
        }
    }

    public static <E extends SimpleEntity> E fillCreatorAndModifier(E entity, UserService service) {
        User user = service.currentLoginUser();
        if (ObjectUtil.isNull(entity.getCreatedUser())) {
            entity.setCreatedUser(user);
        }
        entity.setModifiedUser(user);
        return entity;
    }
}
