package ru.soune.nocopy.service.dadata;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.soune.nocopy.dto.dadata.DaDataResponse;
import ru.soune.nocopy.dto.dadata.DaDataSuggestion;
import ru.soune.nocopy.dto.dadata.DaDataWrapper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class DaDataService {

    @Value("${dadata.api-key}")
    private String apiKey ;

    @Value("${dadata.url}")
    private String dadataUrl;

    private final OkHttpClient httpClient;

    public DaDataService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .callTimeout(20, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public DaDataResponse callDaData(String inn) throws IOException {
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalStateException("SearchAPI key not configured");
        }

        String jsonBody = String.format("{\"query\": \"%s\"}", inn);

        Request request = new Request.Builder()
                .url(dadataUrl)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody))
                .header("Accept", "application/json")
                .header("Authorization", "Token " + apiKey)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            ResponseBody body = response.body();

            if (body == null) {
                throw new IOException("Empty response body");
            }

            String jsonResponse = body.string();

            ObjectMapper mapper = new ObjectMapper();
            DaDataWrapper wrapper = mapper.readValue(jsonResponse, DaDataWrapper.class);

            DaDataResponse daDataResponse = new DaDataResponse();

            if (wrapper.getSuggestions() != null && !wrapper.getSuggestions().isEmpty()) {
                DaDataSuggestion suggestion = wrapper.getSuggestions().get(0);

                daDataResponse.setCompanyName(suggestion.getValue());

                if (suggestion.getData() != null) {
                    daDataResponse.setInn(suggestion.getData().getInn());

                    if (suggestion.getData().getAddress() != null) {
                        daDataResponse.setAddress(suggestion.getData().getAddress().getValue());
                    }
                }
            }

            return daDataResponse;
        }
    }
}
