package com.my.framework.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class SchemaInterceptor implements Interceptor {

    private String defaultSchema;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        String originalSql = statementHandler.getBoundSql().getSql();

        // Modify the SQL to include the default schema
        String modifiedSql = addSchemaToSql(originalSql);

        // Use reflection to modify the SQL in BoundSql
        Field sqlField = statementHandler.getBoundSql().getClass().getDeclaredField("sql");
        sqlField.setAccessible(true);
        sqlField.set(statementHandler.getBoundSql(), modifiedSql);

        return invocation.proceed();
    }

    private String addSchemaToSql(String originalSql) {
        return originalSql.replaceAll("(?i)(FROM|JOIN|UPDATE|INTO|TABLE)\\s+([a-zA-Z0-9_]+)", "$1 " + defaultSchema + ".$2");
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.defaultSchema = properties.getProperty("defaultSchema");
    }
}
