package com.dano.test1.network

import android.content.Context
import android.util.Log
import com.dano.test1.AES256Helper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream

object DatabaseDownloader {

    private const val DB_NAME = "questionnaire_database"
    private const val SERVER_DOWNLOAD_URL = "https://daniel-ocks.de/qdb/downloadFull.php"

    private val client = OkHttpClient()

    // Neue Variante mit Callback
    fun downloadAndReplaceDatabase(context: Context, token: String, onDone: ((Boolean) -> Unit)? = null) {
        CoroutineScope(Dispatchers.IO).launch {
            var ok = false
            try {
                val request = Request.Builder()
                    .url(SERVER_DOWNLOAD_URL)
                    .header("Authorization", "Bearer $token")
                    .build()

                val response = client.newCall(request).execute()
                if (!response.isSuccessful) {
                    Log.e("DOWNLOAD", "HTTP ${response.code}")
                    withContext(Dispatchers.Main) { onDone?.invoke(false) }
                    return@launch
                }

                val encFile = File(context.cacheDir, "downloaded_database.enc")
                response.body?.byteStream()?.use { input ->
                    FileOutputStream(encFile).use { output -> input.copyTo(output) }
                }

                val decryptedBytes = AES256Helper.decryptFileWithToken(encFile, token)
                val dbFile = context.getDatabasePath(DB_NAME)
                if (dbFile.exists()) dbFile.delete()
                FileOutputStream(dbFile).use { it.write(decryptedBytes) }

                Log.d("DOWNLOAD", "DB erfolgreich ersetzt")
                ok = true
            } catch (e: Exception) {
                Log.e("DOWNLOAD", "Fehler", e)
            } finally {
                withContext(Dispatchers.Main) { onDone?.invoke(ok) }
            }
        }
    }

    // Abwärtskompatible alte Signatur
    fun downloadAndReplaceDatabase(context: Context, token: String) {
        downloadAndReplaceDatabase(context, token, null)
    }
}
