package de.softwareapp_hb.privateqrscanner.data.repository

import de.softwareapp_hb.privateqrscanner.data.local.ScanDao
import de.softwareapp_hb.privateqrscanner.data.local.ScanEntity
import de.softwareapp_hb.privateqrscanner.domain.ScanRecord
import de.softwareapp_hb.privateqrscanner.settings.SettingsRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

class ScanRepository(
    private val dao: ScanDao,
    private val settingsRepository: SettingsRepository
) {
    fun observeHistory(): Flow<List<ScanRecord>> = dao.observeAll().map { list ->
        list.map { entity ->
            ScanRecord(
                id = entity.id,
                content = entity.content,
                type = entity.type,
                timestamp = entity.timestamp
            )
        }
    }

    suspend fun maybeSaveScan(content: String, type: String) {
        val historyEnabled = settingsRepository.historyEnabled.first()
        if (!historyEnabled) return
        dao.insert(
            ScanEntity(
                content = content,
                type = type,
                timestamp = System.currentTimeMillis()
            )
        )
    }

    suspend fun deleteById(id: Long) = dao.deleteById(id)

    suspend fun clearAll() = dao.clearAll()
}
