package com.android.trisolarisserver.component import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import org.springframework.web.client.RestTemplate import org.springframework.web.util.UriComponentsBuilder @Component class PostalPincodeClient( private val restTemplate: RestTemplate, private val objectMapper: ObjectMapper, @Value("\${pincode.postal.baseUrl:https://api.postalpincode.in}") private val baseUrl: String ) { private val logger = LoggerFactory.getLogger(PostalPincodeClient::class.java) fun resolve(pinCode: String): PincodeLookupResult { return try { val first = fetch(baseUrl, pinCode) if (first.resolvedCityState != null) return first if (first.status == "ERROR" && baseUrl.startsWith("https://")) { val httpUrl = baseUrl.replaceFirst("https://", "http://") val second = fetch(httpUrl, pinCode) if (second.resolvedCityState != null) return second return second } first } catch (ex: Exception) { logger.warn("Postalpincode lookup failed: {}", ex.message) PincodeLookupResult(null, null, "ERROR", "postalpincode.in", ex.message) } } private fun fetch(base: String, pinCode: String): PincodeLookupResult { val url = UriComponentsBuilder.fromUriString(base) .path("/pincode/{pin}") .buildAndExpand(pinCode) .toUriString() val response = restTemplate.getForEntity(url, String::class.java) val body = response.body ?: return PincodeLookupResult(null, null, "EMPTY_BODY", "postalpincode.in") val resolved = parseCityState(body) val status = if (resolved == null) "ZERO_RESULTS" else "OK" return PincodeLookupResult(resolved, body, status, "postalpincode.in") } private fun parseCityState(body: String): String? { val root = objectMapper.readTree(body) if (!root.isArray || root.isEmpty) return null val first = root.first() val status = first.path("Status").asText(null) if (!status.equals("Success", true)) return null val offices = first.path("PostOffice") if (!offices.isArray || offices.isEmpty) return null val office = chooseOffice(offices) ?: return null val district = office.path("District").asText(null) val state = office.path("State").asText(null) if (district.isNullOrBlank() && state.isNullOrBlank()) return null return listOfNotNull(district?.ifBlank { null }, state?.ifBlank { null }).joinToString(", ") } private fun chooseOffice(offices: JsonNode): JsonNode? { val delivery = offices.firstOrNull { it.path("DeliveryStatus").asText("").equals("Delivery", true) } return delivery ?: offices.firstOrNull() } }