package com.ruoyi.info.collection.mapper;

import com.ruoyi.info.collection.domain.dto.CcdiAccountInfoQueryDTO;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.TypeAliasRegistry;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CcdiAccountInfoMapperTest {

    private static final String RESOURCE = "mapper/info/collection/CcdiAccountInfoMapper.xml";

    @Test
    void selectAccountInfoPage_shouldReadAnalysisColumnsFromAccountInfoTableOnly() throws Exception {
        MappedStatement mappedStatement = loadMappedStatement(
            "com.ruoyi.info.collection.mapper.CcdiAccountInfoMapper.selectAccountInfoPage");

        String sql = renderSql(mappedStatement, Map.of("query", new CcdiAccountInfoQueryDTO())).toLowerCase();

        assertTrue(sql.contains("from ccdi_account_info ai"), sql);
        assertFalse(sql.contains("ccdi_account_result"), sql);
        assertTrue(sql.contains("ai.is_self_account as isactualcontrol"), sql);
        assertTrue(sql.contains("ai.monthly_avg_trans_count as avgmonthtxncount"), sql);
        assertTrue(sql.contains("ai.trans_risk_level as txnrisklevel"), sql);
        assertTrue(sql.contains("ai.owner_type <> 'credit_customer'"), sql);
    }

    @Test
    void selectAccountInfoPage_shouldFilterByAccountNo() throws Exception {
        MappedStatement mappedStatement = loadMappedStatement(
            "com.ruoyi.info.collection.mapper.CcdiAccountInfoMapper.selectAccountInfoPage");
        CcdiAccountInfoQueryDTO queryDTO = new CcdiAccountInfoQueryDTO();
        queryDTO.setAccountNo("6222");

        String sql = renderSql(mappedStatement, Map.of("query", queryDTO)).toLowerCase();

        assertTrue(sql.contains("ai.account_no like concat('%', ?, '%')"), sql);
    }

    private MappedStatement loadMappedStatement(String statementId) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setEnvironment(new Environment("test", new JdbcTransactionFactory(), new NoOpDataSource()));
        registerTypeAliases(configuration.getTypeAliasRegistry());
        configuration.getLanguageRegistry().register(XMLLanguageDriver.class);
        configuration.addMapper(CcdiAccountInfoMapper.class);

        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(RESOURCE)) {
            XMLMapperBuilder xmlMapperBuilder =
                new XMLMapperBuilder(inputStream, configuration, RESOURCE, configuration.getSqlFragments());
            xmlMapperBuilder.parse();
        }
        return configuration.getMappedStatement(statementId);
    }

    private String renderSql(MappedStatement mappedStatement, Map<String, Object> params) {
        BoundSql boundSql = mappedStatement.getBoundSql(new HashMap<>(params));
        return boundSql.getSql().replaceAll("\\s+", " ").trim();
    }

    private void registerTypeAliases(TypeAliasRegistry typeAliasRegistry) {
        typeAliasRegistry.registerAlias("map", Map.class);
    }

    private static class NoOpDataSource implements DataSource {

        @Override
        public java.sql.Connection getConnection() {
            throw new UnsupportedOperationException("Not required for SQL rendering tests");
        }

        @Override
        public java.sql.Connection getConnection(String username, String password) {
            throw new UnsupportedOperationException("Not required for SQL rendering tests");
        }

        @Override
        public java.io.PrintWriter getLogWriter() {
            return null;
        }

        @Override
        public void setLogWriter(java.io.PrintWriter out) {
        }

        @Override
        public void setLoginTimeout(int seconds) {
        }

        @Override
        public int getLoginTimeout() {
            return 0;
        }

        @Override
        public java.util.logging.Logger getParentLogger() {
            return java.util.logging.Logger.getGlobal();
        }

        @Override
        public <T> T unwrap(Class<T> iface) {
            throw new UnsupportedOperationException("Not supported");
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) {
            return false;
        }
    }
}
