package com.qqchen.deploy.backend.framework.utils;

import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

public class EntityPathResolver {
    private static final Logger log = LoggerFactory.getLogger(EntityPathResolver.class);

    public static Path<?> getPath(EntityPath<?> entityPath, String fieldName) {
        try {
            // 1. 首先尝试直接获取字段
            try {
                Field field = entityPath.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                return (Path<?>) field.get(entityPath);
            } catch (NoSuchFieldException e) {
                // 2. 尝试从_super中获取
                Field superField = entityPath.getClass().getDeclaredField("_super");
                superField.setAccessible(true);
                Object superInstance = superField.get(entityPath);

                if (superInstance != null) {
                    try {
                        // 直接从_super中获取字段
                        Field field = superInstance.getClass().getDeclaredField(fieldName);
                        field.setAccessible(true);
                        return (Path<?>) field.get(superInstance);
                    } catch (NoSuchFieldException ex) {
                        // 3. 尝试从_super.entity中获取
                        try {
                            Field entityField = superInstance.getClass().getDeclaredField("entity");
                            entityField.setAccessible(true);
                            Object entityInstance = entityField.get(superInstance);

                            if (entityInstance != null) {
                                Field field = entityInstance.getClass().getDeclaredField(fieldName);
                                field.setAccessible(true);
                                return (Path<?>) field.get(entityInstance);
                            }
                        } catch (NoSuchFieldException | IllegalAccessException innerEx) {
                            log.debug("Field {} not found in _super.entity", fieldName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error resolving path for field {}: {}", fieldName, e.getMessage());
        }

        return null;
    }
}