package com.eshore.gringotts.web.helper;

import cn.hutool.core.util.ObjectUtil;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity;
import com.eshore.gringotts.web.domain.base.entity.CheckingNeededEntity_;
import com.eshore.gringotts.web.domain.entity.CheckOrder;
import com.eshore.gringotts.web.domain.entity.CheckOrder_;
import com.eshore.gringotts.web.domain.entity.User;
import java.util.function.Supplier;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
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 Predicate checkNeededEntityPrediction(Root<? extends CheckingNeededEntity> root, CriteriaBuilder builder, User loginUser) {
        return builder.or(
                builder.and(
                        builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
                        builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole())
                ),
                builder.and(
                        builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
                        builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser)
                )
        );
    }
}
