package com.jaytux.simd.data

import com.jaytux.simd.DotEnv
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.prefs.Preferences

object Database {
    val db by lazy {
        val db = Database.connect(
            url = DotEnv["DATABASE_URL"] ?: throw DotEnv.DotEnvException("DATABASE_URL"),
            driver = DotEnv["DATABASE_DRIVER"] ?: throw DotEnv.DotEnvException("DATABASE_DRIVER"),
            user = DotEnv["DATABASE_USER"] ?: "",
            password = DotEnv["DATABASE_PASSWORD"] ?: "",
        )
        transaction {
            SchemaUtils.create(Techs, CppTypes, Categories, CPUIDs, Intrinsics,
                IntrinsicArguments, IntrinsicInstructions, Platforms, Performances)
        }

        db
    }

    fun reset() {
        db
        transaction {
            SchemaUtils.drop(Techs, CppTypes, Categories, CPUIDs, Intrinsics,
                IntrinsicArguments, IntrinsicInstructions, Platforms, Performances)
            SchemaUtils.create(Techs, CppTypes, Categories, CPUIDs, Intrinsics,
                IntrinsicArguments, IntrinsicInstructions, Platforms, Performances)
        }
    }
}