package de.softwareapp_hb.privateqrscanner.util

import de.softwareapp_hb.privateqrscanner.domain.ScanRecord
import java.text.DateFormat
import java.util.Date

object HistoryExportFormatter {
    fun formatText(history: List<ScanRecord>): String {
        if (history.isEmpty()) return ""
        val formatter = DateFormat.getDateTimeInstance()
        return history.joinToString(separator = "\n\n") { item ->
            val time = formatter.format(Date(item.timestamp))
            "$time\n${item.type}\n${item.content}"
        }
    }

    fun formatCsv(history: List<ScanRecord>): String {
        if (history.isEmpty()) return ""
        val formatter = DateFormat.getDateTimeInstance()
        val header = "timestamp,type,content"
        val rows = history.joinToString(separator = "\n") { item ->
            val ts = csvEscape(formatter.format(Date(item.timestamp)))
            val type = csvEscape(item.type)
            val content = csvEscape(item.content)
            "$ts,$type,$content"
        }
        return "$header\n$rows"
    }

    fun formatJson(history: List<ScanRecord>): String {
        if (history.isEmpty()) return "[]"
        return history.joinToString(prefix = "[\n", postfix = "\n]", separator = ",\n") { item ->
            val escapedType = jsonEscape(item.type)
            val escapedContent = jsonEscape(item.content)
            "  {\"id\":${item.id},\"timestamp\":${item.timestamp},\"type\":\"$escapedType\",\"content\":\"$escapedContent\"}"
        }
    }

    private fun csvEscape(value: String): String {
        val escaped = value.replace("\"", "\"\"")
        return "\"$escaped\""
    }

    private fun jsonEscape(value: String): String {
        return value
            .replace("\\", "\\\\")
            .replace("\"", "\\\"")
            .replace("\n", "\\n")
    }
}
