package com.ruoyi.system.mapper;

import com.ruoyi.system.domain.IpnLog;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

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

class IpnLogMapperXmlTest {

    @Test
    void mapperPersistsSelectsAndFiltersType() throws IOException {
        Configuration configuration = mapperConfiguration();
        IpnLog query = new IpnLog();
        query.setType("omg");

        BoundSql insert = configuration
                .getMappedStatement("com.ruoyi.system.mapper.IpnLogMapper.insertIpnLog")
                .getBoundSql(query);
        assertTrue(sql(insert).contains("type"));
        assertTrue(insert.getParameterMappings().stream()
                .anyMatch(mapping -> "type".equals(mapping.getProperty())));

        BoundSql select = configuration
                .getMappedStatement("com.ruoyi.system.mapper.IpnLogMapper.selectIpnLogList")
                .getBoundSql(query);
        assertTrue(sql(select).contains("select id, ip, cretim, ipn_log, type from ipn_log"));
        assertTrue(sql(select).contains("type = ?"));
        assertTrue(select.getParameterMappings().stream()
                .anyMatch(mapping -> "type".equals(mapping.getProperty())));
    }

    private Configuration mapperConfiguration() throws IOException {
        Configuration configuration = new Configuration();
        configuration.getTypeAliasRegistry().registerAlias("IpnLog", IpnLog.class);
        String resource = "mapper/system/IpnLogMapper.xml";
        try (InputStream input = getClass().getClassLoader().getResourceAsStream(resource)) {
            assertNotNull(input);
            new XMLMapperBuilder(input, configuration, resource, configuration.getSqlFragments()).parse();
        }
        return configuration;
    }

    private String sql(BoundSql boundSql) {
        return boundSql.getSql().replaceAll("\\s+", " ").trim().toLowerCase(Locale.ROOT);
    }
}
