package top.r3944realms.ltdmanager.utils

import java.io.File

class SqlTemplate private constructor(private val template: String) {

    fun bind(vararg pairs: Pair<String, String>): String {
        var result = template
        for ((key, value) in pairs) {
            result = result.replace("\${$key}", value)
        }
        return result
    }

    companion object {
        private val cache = mutableMapOf<String, SqlTemplate>()

        private val baseDir: String by lazy {
            val configDir = File("config/sql")
            if (!configDir.exists()) configDir.mkdirs()
            configDir.absolutePath
        }

        fun fromFile(path: String): SqlTemplate {
            return cache.getOrPut(path) {
                val file = File(baseDir, path)
                require(file.exists()) {
                    "SQL template not found: ${file.absolutePath}"
                }
                SqlTemplate(file.readText().trimIndent())
            }
        }

        fun clearCache() = cache.clear()
    }
}
