package de.avatic.lcc.service.api;

import de.avatic.lcc.model.zolltarifnummern.ZolltarifnummernResponse;
import de.avatic.lcc.model.zolltarifnummern.ZolltarifnummernResponseEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class ZolltarifnummernApiService {

    private static final Logger logger = LoggerFactory.getLogger(ZolltarifnummernApiService.class);

    private static final String API_V_1 = "https://www.zolltarifnummern.de/api/v1/cnSuggest";
    private final RestTemplate restTemplate;

    public ZolltarifnummernApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Async("customLookupExecutor")
    public CompletableFuture<Set<String>> getDeclarableHsCodes(String incompleteHsCode) {

        try {
            String url = UriComponentsBuilder.fromUriString(API_V_1)
                    .queryParam("term", incompleteHsCode)
                    .queryParam("lang", "en")
                    .encode()
                    .toUriString();

            var resp = restTemplate.getForObject(url, ZolltarifnummernResponse.class);

            if (resp != null && resp.getSuggestions() != null) {
                return CompletableFuture.completedFuture(resp.getSuggestions().stream()
                        .map(ZolltarifnummernResponseEntry::getCode)
                        .filter(s -> s.startsWith(incompleteHsCode))
                        .filter(s -> s.length() >= 10).collect(Collectors.toSet()));
            }

        } catch (Throwable t) {
            logger.error("HS code lookup failed with exception \"{}\"", t.getMessage());
            // just continue
        }

        logger.warn("Unable to load tarif numbers for HS code {}", incompleteHsCode);

        return CompletableFuture.completedFuture(Collections.emptySet());
    }

}
