package com.ylx.massage.mapper;

import org.junit.jupiter.api.Test;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

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

public class TAddressMapperXmlTest {

    @Test
    public void pcUserAddressListSqlOnlyQueriesByOpenId() throws Exception {
        String xml = readMapperXml();

        assertTrue(xml.contains("selectPcUserAddressList"));
        assertTrue(xml.contains("FROM t_address"));
        assertTrue(xml.contains("openid = #{openId}"));
        assertTrue(xml.contains("is_delete = 0"));
        assertTrue(xml.contains("user_type = 1"));
        assertTrue(xml.contains("type = 1"));
        assertTrue(xml.contains("ORDER BY is_default DESC, create_time DESC"));
        assertFalse(xml.contains("user_id = #{userId}"));
    }

    @Test
    public void addressResultMapUsesMerchantAddressColumns() throws Exception {
        String xml = readMapperXml();

        assertTrue(xml.contains("property=\"merchantId\" column=\"merchant_id\""));
        assertTrue(xml.contains("property=\"userType\" column=\"user_type\""));
        assertTrue(xml.contains("property=\"isDefault\" column=\"is_default\""));
        assertFalse(xml.contains("property=\"isDefault\" column=\"type\""));
    }

    @Test
    public void currentMerchantAddressOnlyQueriesRealMerchantAddress() throws Exception {
        String xml = readMapperXml();
        String selectSql = extractSelect(xml, "selectCurrentMerchantRealAddress");

        assertTrue(selectSql.contains("merchant_id = #{merchantId}"));
        assertTrue(selectSql.contains("user_type = 2"));
        assertTrue(selectSql.contains("type = 1"));
        assertTrue(selectSql.contains("is_delete = 0"));
        assertTrue(selectSql.contains("ORDER BY is_default DESC, create_time DESC"));
        assertTrue(selectSql.contains("LIMIT 1"));
        assertFalse(selectSql.contains("AND type = 2"));
    }

    private String readMapperXml() throws Exception {
        try (InputStream inputStream = getClass().getClassLoader()
                .getResourceAsStream("mapper/address/TAddressMapper.xml")) {
            assertNotNull(inputStream, "TAddressMapper.xml should exist in test classpath");
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }

    private String extractSelect(String xml, String selectId) {
        String startTag = "<select id=\"" + selectId + "\"";
        int start = xml.indexOf(startTag);
        assertTrue(start >= 0, selectId + " should exist");
        int end = xml.indexOf("</select>", start);
        assertTrue(end > start, selectId + " should have closing select tag");
        return xml.substring(start, end);
    }
}
