package com.easyagents.engine.es;

import co.elastic.clients.elasticsearch.core.SearchRequest;
import com.easyagents.core.document.Document;
import com.easyagents.search.engine.service.KeywordSearchMetadataKeys;
import com.easyagents.search.engine.service.KeywordSearchRequest;
import org.junit.Assert;
import org.junit.Test;

import java.util.Map;

public class ElasticSearcherQueryBuilderTest {

    @Test
    public void shouldBuildSearchRequestWithMultiMatchAndKnowledgeFilter() {
        ElasticSearcher searcher = new ElasticSearcher(config());
        KeywordSearchRequest request = KeywordSearchRequest.of("客服", 5);
        request.setKnowledgeId("100");

        SearchRequest searchRequest = searcher.buildSearchRequest(request);

        Assert.assertEquals(5, searchRequest.size().intValue());
        Assert.assertNotNull(searchRequest.query().bool());
        Assert.assertEquals(1, searchRequest.query().bool().must().size());
        Assert.assertNotNull(searchRequest.query().bool().must().get(0).multiMatch());
        Assert.assertEquals(2, searchRequest.query().bool().must().get(0).multiMatch().fields().size());
        Assert.assertEquals(1, searchRequest.query().bool().filter().size());
        Assert.assertEquals("knowledgeId", searchRequest.query().bool().filter().get(0).term().field());
    }

    @Test
    public void shouldExtractKnowledgeIdToTopLevelSource() {
        ElasticSearcher searcher = new ElasticSearcher(config());
        Document document = new Document();
        document.setId("1");
        document.setTitle("title");
        document.setContent("content");
        document.addMetadata(KeywordSearchMetadataKeys.KNOWLEDGE_ID, "100");

        Map<String, Object> source = searcher.buildSource(document);

        Assert.assertEquals("100", source.get(KeywordSearchMetadataKeys.KNOWLEDGE_ID));
        Assert.assertTrue(source.get("metadataMap") instanceof Map);
    }

    private ESConfig config() {
        ESConfig config = new ESConfig();
        config.setHost("http://127.0.0.1:9200");
        config.setUserName("elastic");
        config.setPassword("elastic");
        config.setIndexName("easyflow");
        return config;
    }
}
