package com.yeejoin.amos.boot.module.common.biz.service.impl;

import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.yeejoin.amos.boot.module.common.api.constant.TZSCommonConstant.ES_INDEX_NAME_EQUIPMENT_INFO;

@Service
@RequiredArgsConstructor
public class ESEquipmentInfoService {

    private final RestHighLevelClient restHighLevelClient;

    public List<String> findSequenceNbrByIds(List<String> ids) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder()
                .query(QueryBuilders.termsQuery("SEQUENCE_NBR.keyword", ids))
                .fetchSource(false);
        SearchRequest request = new SearchRequest(ES_INDEX_NAME_EQUIPMENT_INFO)
                .source(sourceBuilder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return Arrays.stream(response.getHits().getHits())
                    .map(SearchHit::getId)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
