package tech.easyflow.agent.config;

import org.junit.Assert;
import org.junit.Test;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * {@link AgentInteractionConfigSupport} 单元测试。
 */
public class AgentInteractionConfigSupportTest {

    /**
     * 验证空配置可以转换为稳定结构。
     */
    @Test
    public void shouldNormalizeEmptyConfig() {
        Map<String, Object> normalized = AgentInteractionConfigSupport.normalize(null);

        Assert.assertEquals("", normalized.get("welcomeMessage"));
        Assert.assertEquals(List.of(), normalized.get("suggestedQuestions"));
        Assert.assertEquals("", normalized.get("inputPlaceholder"));
    }

    /**
     * 验证空问题会被过滤，合法问题会去除首尾空白并保持顺序。
     */
    @Test
    public void shouldNormalizeSuggestedQuestions() {
        Map<String, Object> source = new LinkedHashMap<>();
        source.put("welcomeMessage", "  欢迎使用\n智能助手  ");
        source.put("suggestedQuestions", List.of("  第一个问题  ", "", " 第二个问题"));
        source.put("inputPlaceholder", "  请输入问题  ");

        Map<String, Object> normalized = AgentInteractionConfigSupport.normalize(source);

        Assert.assertEquals("欢迎使用\n智能助手", normalized.get("welcomeMessage"));
        Assert.assertEquals(List.of("第一个问题", "第二个问题"), normalized.get("suggestedQuestions"));
        Assert.assertEquals("请输入问题", normalized.get("inputPlaceholder"));
    }

    /**
     * 验证重复问题会被拒绝。
     */
    @Test
    public void shouldRejectDuplicateQuestionsAfterTrim() {
        Map<String, Object> source = Map.of(
            "suggestedQuestions", List.of("如何使用？", "  如何使用？ ")
        );

        assertBusinessException(() -> AgentInteractionConfigSupport.normalize(source));
    }

    /**
     * 验证多行输入提示会被拒绝。
     */
    @Test
    public void shouldRejectMultilinePlaceholder() {
        Map<String, Object> source = Map.of("inputPlaceholder", "第一行\n第二行");

        assertBusinessException(() -> AgentInteractionConfigSupport.normalize(source));
    }

    /**
     * 验证问题数量不能超过上限。
     */
    @Test
    public void shouldRejectTooManyQuestions() {
        Map<String, Object> source = Map.of(
            "suggestedQuestions",
            List.of("问题1", "问题2", "问题3", "问题4", "问题5", "问题6", "问题7")
        );

        assertBusinessException(() -> AgentInteractionConfigSupport.normalize(source));
    }

    /**
     * 断言操作会抛出业务异常。
     *
     * @param action 待执行操作
     */
    private void assertBusinessException(Runnable action) {
        try {
            action.run();
            Assert.fail("应抛出 BusinessException");
        } catch (BusinessException expected) {
            Assert.assertNotNull(expected.getMessage());
        }
    }
}
