package com.gestoreasy.services

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit

/**
 * Serviço para busca de endereço por CEP usando ViaCEP
 */
class CepService {
    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()
    
    private val baseUrl = "https://viacep.com.br/ws"
    
    data class Address(
        val logradouro: String,
        val complemento: String?,
        val bairro: String,
        val cidade: String,
        val estado: String,
        val cep: String
    )
    
    suspend fun searchCep(cep: String): Address? = withContext(Dispatchers.IO) {
        try {
            val cleanCep = cep.replace(Regex("[^0-9]"), "")
            
            if (cleanCep.length != 8) {
                return@withContext null
            }
            
            val request = Request.Builder()
                .url("$baseUrl/$cleanCep/json")
                .get()
                .build()
            
            val response = client.newCall(request).execute()
            
            if (!response.isSuccessful) {
                return@withContext null
            }
            
            val json = JSONObject(response.body?.string() ?: "")
            
            if (json.has("erro")) {
                return@withContext null
            }
            
            return@withContext Address(
                logradouro = json.optString("logradouro", ""),
                complemento = json.optString("complemento", "").takeIf { it.isNotEmpty() },
                bairro = json.optString("bairro", ""),
                cidade = json.optString("localidade", ""),
                estado = json.optString("uf", ""),
                cep = cleanCep
            )
        } catch (e: Exception) {
            e.printStackTrace()
            return@withContext null
        }
    }
}

