package cn.stylefeng.team.meta.db.util;

import cn.stylefeng.team.meta.db.constants.QueryBuilderConstants;

import java.text.SimpleDateFormat;
import java.util.*;

public class QueryConditionUtil {

    public static void validateField(String field) {
        if (!field.matches(QueryBuilderConstants.FIELD_NAME_VALIDATE)) {
            throw new IllegalArgumentException("Invalid field name: " + field);
        }
    }

    public static void validateOperator(String operator) {
        Set<String> allowedOperators = new HashSet<>(QueryBuilderConstants.OPERATORS);
        if (!allowedOperators.contains(operator.toUpperCase())) {
            throw new IllegalArgumentException("Invalid operator: " + operator);
        }
    }

    public static void validateLogic(String logic) {
        if (!"AND".equalsIgnoreCase(logic) && !"OR".equalsIgnoreCase(logic)) {
            throw new IllegalArgumentException("Logic must be AND or OR");
        }
    }

    public static String escapeValue(Object value) {
        if (value instanceof String) {
            return "'" + ((String) value).replace("'", "''") + "'";
        } else if (value instanceof Number) {
            return value.toString();
        } else if (value instanceof Boolean) {
            return (Boolean) value ? "1" : "0";
        } else if (value instanceof Date) {
            return "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value) + "'";
        } else if (value instanceof List) {
            List<?> list = (List<?>) value;
            List<String> escaped = new ArrayList<>();
            for (Object item : list) {
                escaped.add(escapeValue(item));
            }
            return "(" + String.join(", ", escaped) + ")";
        } else {
            throw new IllegalArgumentException("Unsupported value type: " + value.getClass().getSimpleName());
        }
    }

    public static String removeEndingAndOr(String input) {

        return input.replaceAll("(?i)\\b(and|or)\\b\\s*$", "").trim();
    }

}
