package com.gamedog.vididin.netbase

import okhttp3.ResponseBody
import retrofit2.HttpException
import java.io.IOException

object NetworkUtil {

    private val apiService: ApiService by lazy {
        RetrofitUtil.getRetrofitInstance().create(ApiService::class.java)
    }

    fun apiservice(): ApiService {
        return apiService
    }

    suspend fun get(
        url: String,
        headers: Map<String, String> = emptyMap(),
        params: Map<String, String> = emptyMap()
    ): Result<ResponseBody> {
        return executeRequest {
            apiService.getRequest(url, headers, params)
        }
    }


    suspend fun post(
        url: String,
        headers: Map<String, String> = emptyMap(),
        params: Map<String, String> = emptyMap(),
        JoinedPurchaseIds : List<Int> = emptyList<Int>()
    ): Result<ResponseBody> {
        return executeRequest {
            apiService.postRequest(url, headers, params, JoinedPurchaseIds)
        }
    }


    suspend fun postJson(
        url: String,
        body: Any,
        headers: Map<String, String> = emptyMap()
    ): Result<ResponseBody> {
        return executeRequest {
            apiService.postJsonRequest(url, headers, body)
        }
    }

    suspend fun <T> callApi(apiCall: suspend () -> T): Result<T> {
        return try {
            Result.Success(apiCall())
        } catch (e: IOException) {
            Result.Error(e, "网络连接失败，请检查网络设置")
        } catch (e: HttpException) {
            Result.Error(e, "服务器错误: ${e.code()}")
        } catch (e: Exception) {
            Result.Error(e, "未知错误: ${e.message}")
        }
    }

    private suspend fun <T> executeRequest(requestBlock: suspend () -> T): Result<T> {
        return try {
            Result.Success(requestBlock())
        } catch (e: IOException) {
            Result.Error(e, "网络连接失败，请检查网络设置")
        } catch (e: HttpException) {
            Result.Error(e, "服务器错误: ${e.code()}")
        } catch (e: Exception) {
            Result.Error(e, "未知错误: ${e.message}")
        }
    }




}