package com.example.mystictale.resources

import kotlinx.coroutines.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject

suspend fun getUserIdByEmail(emailUser: String): String? = withContext(Dispatchers.IO) {
    val client = OkHttpClient()
    val url = "https://eykhnnlgofgxdzlixydt.supabase.co/auth/v1/admin/users"
    val request = Request.Builder()
        .url(url)
        .addHeader(
            "Authorization",
            "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV5a2hubmxnb2ZneGR6bGl4eWR0Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcyOTIzNDg3OCwiZXhwIjoyMDQ0ODEwODc4fQ.Y_4IElNlvVo59iYJ4Wa9AJyP0wT7z3ysB50vxzL9bQU"
        )
        .addHeader(
            "apikey",
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImV5a2hubmxnb2ZneGR6bGl4eWR0Iiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTcyOTIzNDg3OCwiZXhwIjoyMDQ0ODEwODc4fQ.Y_4IElNlvVo59iYJ4Wa9AJyP0wT7z3ysB50vxzL9bQU"
        )
        .build()

    try {
        val response = client.newCall(request).execute()
        val responseBody = response.body?.string()

        // Проверяем код ответа
        if (response.code != 200 || responseBody.isNullOrEmpty()) {
            println("Ошибка: ${response.code}, Сообщение: $responseBody")
            return@withContext null
        }

        // Обрабатываем JSON-ответ
        val jsonResponse = JSONObject(responseBody)
        val usersArray = jsonResponse.optJSONArray("users") ?: return@withContext null

        for (i in 0 until usersArray.length()) {
            val user = usersArray.getJSONObject(i)
            val email = user.optString("email")
            if (email == emailUser) {
                return@withContext user.optString("id")
            }
        }

        return@withContext null // Если email не найден
    } catch (e: Exception) {
        e.printStackTrace()
        return@withContext null
    }
}