package api

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class TetrisClient(okHttpClient: OkHttpClient) {
    private val api: TetrisAPI


    init {
        // Create Gson object with lenient policy
        val gson = GsonBuilder()
            .setLenient()
            .create()

        // Create Retrofit instance
        val retrofit = Retrofit.Builder()
            .baseUrl("https://ch.tetr.io/api/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okHttpClient)
            .build()


        // Create API instance
        api = retrofit.create(TetrisAPI::class.java)
    }

    fun getUsers(callback: (List<User>?, Throwable?) -> Unit) {
        api.getAllUsers().enqueue(object : Callback<UserResponse> {
            override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
                if (response.isSuccessful) {
                    // API call successful, parse response body
                    val users = response.body()?.data?.users
                    callback(users, null)
                } else {
                    // API call failed, handle error
                    val error = Exception("API call failed with code ${response.code()}")
                    callback(null, error)
                }
            }

            override fun onFailure(call: Call<UserResponse>, t: Throwable) {
                // API call failed, handle error
                callback(null, t)
            }
        })
    }
}