package com.eactive.eai.rms.kakao.rolling;

import com.eactive.eai.rms.ext.kakaocard.cm.KakaoCardCmDeploySuffixContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EmptyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.regex.Pattern;

public class DeployTableInterceptorImpl extends EmptyInterceptor implements DeployTableInterceptor {

    protected static final String[] TARGET_TABLE_NAMES = new String[] { "tseaihe01", "tseaihe02", "tseaims02",
            "tseaifr01", "tseaifr03", "tseaihs04", "tseaihs05", "tseaifr06", "tseaitr07", "tseaitr08", "tseaitr01",
            "tseaitr02", "tseaitr03", "tseaihs14", "tseaihs15" };


    private static final Pattern rollingSuffixedTableName = Pattern.compile("tseai....(_\\d+)?");


    @Lazy
    @Autowired
    private transient KakaoCardCmDeploySuffixContextHolder kakaoCardCmDeploySuffixContextHolder;

    @Override
    public String onPrepareStatement(String sql) {
        if (!StringUtils.containsAny(sql, TARGET_TABLE_NAMES) || !rollingSuffixedTableName.matcher(sql).find()) {
            return sql;
        }
        String deploySuffix = kakaoCardCmDeploySuffixContextHolder.getDeploySuffix();
        if (StringUtils.isBlank(deploySuffix)) {
            return sql;
        }
        for (String tableName : TARGET_TABLE_NAMES) {
            sql = sql.replaceAll(tableName + "(_\\d+)?", tableName + deploySuffix);
        }
        return sql;
    }

}
