package com.safecheckin.app.data.api

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.*
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

val Context.serverDataStore: DataStore<Preferences> by preferencesDataStore(name = "server_config")

class ApiClient(private val context: Context) {

    companion object {
        private const val DEFAULT_BASE_URL = "http://localhost:8000"

        val BASE_URL_KEY = stringPreferencesKey("base_url")
        val USER_ID_KEY = intPreferencesKey("user_id")
        val USER_EMAIL_KEY = stringPreferencesKey("user_email")
        val IS_LOGGED_IN_KEY = booleanPreferencesKey("is_logged_in")
    }

    // 服务器地址配置
    val baseUrl: Flow<String> = context.serverDataStore.data.map {
        it[BASE_URL_KEY] ?: DEFAULT_BASE_URL
    }

    suspend fun setBaseUrl(url: String) {
        context.serverDataStore.edit { it[BASE_URL_KEY] = url }
    }

    // 用户登录状态
    val isLoggedIn: Flow<Boolean> = context.serverDataStore.data.map {
        it[IS_LOGGED_IN_KEY] ?: false
    }

    val userId: Flow<Int> = context.serverDataStore.data.map {
        it[USER_ID_KEY] ?: -1
    }

    val userEmail: Flow<String> = context.serverDataStore.data.map {
        it[USER_EMAIL_KEY] ?: ""
    }

    suspend fun saveLoginState(userId: Int, email: String) {
        context.serverDataStore.edit {
            it[USER_ID_KEY] = userId
            it[USER_EMAIL_KEY] = email
            it[IS_LOGGED_IN_KEY] = true
        }
    }

    suspend fun clearLoginState() {
        context.serverDataStore.edit {
            it[USER_ID_KEY] = -1
            it[USER_EMAIL_KEY] = ""
            it[IS_LOGGED_IN_KEY] = false
        }
    }

    // 创建 Retrofit 实例（协程版，正确读取 Flow 值）
    suspend fun createApi(): SafeCheckInApi {
        val url = baseUrl.first()  // 修复：使用 first() 取实际值，而非 toString()
        return buildApi(url)
    }

    // 同步获取 API（用于已知 URL 的场合，如登录时）
    fun createApiSync(baseUrl: String): SafeCheckInApi {
        return buildApi(baseUrl)
    }

    private fun buildApi(url: String): SafeCheckInApi {
        val logging = HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
        val client = OkHttpClient.Builder()
            .addInterceptor(logging)
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .build()

        return Retrofit.Builder()
            .baseUrl(url.trimEnd('/') + "/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(SafeCheckInApi::class.java)
    }
}
