@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.model.repository

import android.content.Context
import eu.gaudian.translator.model.communication.ApiLogEntry
import eu.gaudian.translator.utils.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ApiLogRepository(context: Context) {
    private val dataStore = context.dataStore

    fun getLogs(): Flow<List<ApiLogEntry>> = dataStore.loadObjectList(ApiStoreKeys.API_LOGS_KEY)

    suspend fun addLog(entry: ApiLogEntry, maxKeep: Int = 200) {
        withContext(Dispatchers.IO) {
            try {
                val current = getLogs().first()
                val updated = (current + entry).takeLast(maxKeep)
                dataStore.saveObjectList(ApiStoreKeys.API_LOGS_KEY, updated)
            } catch (e: Exception) {
                Log.e("ApiLogRepository", "Failed to add log", e)
            }
        }
    }

    suspend fun clear() {
        withContext(Dispatchers.IO) {
            dataStore.clear(ApiStoreKeys.API_LOGS_KEY)
        }
    }
}

// Separate object to avoid cluttering the global DataStoreKeys if needed
object ApiStoreKeys {
    val API_LOGS_KEY = DataStoreKeys.API_LOGS_KEY
}