package com.yeejoin.amos.boot.module.tcm.biz.utils;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.ArrayList;
import java.util.List;

public class EnhancedDynamicQueryBuilder {
    private final List<QueryBuilder> initialClauses = new ArrayList<>();
    private String groupLogic; // "AND" 或 "OR"
    private final List<QueryBuilder> mustClauses = new ArrayList<>();
    private final List<QueryBuilder> shouldClauses = new ArrayList<>();
    private final List<QueryBuilder> mustNotClauses = new ArrayList<>();

    public EnhancedDynamicQueryBuilder() {
        this("AND"); // 默认组间关系为AND
    }

    public EnhancedDynamicQueryBuilder(String groupLogic) {
        this.groupLogic = groupLogic != null ? groupLogic : "AND";
    }

    /**
     * 添加条件，自动处理第一个条件为null的情况
     * @param query 查询条件
     * @param logic 逻辑关系 (AND/OR/NOT)，第一个条件可为null
     */
    public EnhancedDynamicQueryBuilder add(QueryBuilder query, String logic) {
        if (logic == null) {
            if (isEmpty()) {
                // 第一个条件，默认作为must条件
                mustClauses.add(query);
            } else {
                // 后续条件未指定逻辑，使用组间默认逻辑
                if ("OR".equalsIgnoreCase(groupLogic)) {
                    shouldClauses.add(query);
                } else {
                    mustClauses.add(query);
                }
            }
        } else {
            switch (logic.toUpperCase()) {
                case "AND":
                    mustClauses.add(query);
                    break;
                case "OR":
                    shouldClauses.add(query);
                    break;
                case "NOT":
                    mustNotClauses.add(query);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported logic: " + logic);
            }
        }
        return this;
    }

    public BoolQueryBuilder build() {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 处理must条件
        mustClauses.forEach(boolQuery::must);

        // 处理should条件
        if (!shouldClauses.isEmpty()) {
            shouldClauses.forEach(boolQuery::should);
            // 如果没有must条件，至少满足一个should
            if (mustClauses.isEmpty()) {
                boolQuery.minimumShouldMatch(1);
            }
        }

        // 处理mustNot条件
        mustNotClauses.forEach(boolQuery::mustNot);

        return boolQuery;
    }

    private boolean isEmpty() {
        return mustClauses.isEmpty() && shouldClauses.isEmpty() && mustNotClauses.isEmpty();
    }
}