import {config} from "dotenv"
import {Liquibase, LiquibaseLogLevels} from "liquibase"
import {resolve} from "path"

interface PostgresEnvVars {
    host?: string
    port?: string
    db?: string
    sslmode?: string
    options?: string
    user?: string
    pass?: string
}

async function migrate() {
    config()
    const vars: PostgresEnvVars = {}
    for (const variable of Object.keys(process.env)) {
        const value = process.env[variable] || ""
        if (variable.startsWith("PG")) {
            switch (variable) {
                case "PGHOST":
                    vars.host = value
                    break
                case "PGPORT":
                    vars.port = value
                    break
                case "PGDATABASE":
                    vars.db = value
                    break
                case "PGUSER":
                    vars.user = value
                    break
                case "PGPASSWORD":
                    vars.pass = value
                    break
                case "PGOPTIONS":
                    vars.options = value
                    break
                case "PGSSLMODE":
                    vars.sslmode = value
                    break
                default:
                    console.log("Unknown PG* environment variable: " + variable)
            }
        }
    }

    const params = []
    params.push(`ApplicationName=${encodeURIComponent("VoreRPG Migration")}`)
    if (vars.options) {
        params.push(`options=${encodeURIComponent(vars.options)}`)
    }
    if (vars.sslmode) {
        params.push(`sslmode=${encodeURIComponent(vars.sslmode)}`)
    }
    const liquibase = new Liquibase({
        changeLogFile: "liquibase-changelog.yml",
        classpath: resolve("lib/postgresql-42.5.0.jar"),
        liquibase: resolve("node_modules/liquibase/dist/liquibase/liquibase"),
        liquibasePropertiesFile: resolve("liquibase.properties"),
        username: vars.user || process.env.USER || process.env.USERNAME || "postgres",
        password: vars.pass || "",
        logLevel: LiquibaseLogLevels.Debug,
        url: `jdbc:postgresql://`
            + `${vars.host ? encodeURIComponent(vars.host) : ""}${vars.port ? `:${encodeURIComponent(vars.port)}` : ""}`
            + `${vars.db ? `/${encodeURIComponent(vars.db)}` : ""}${params.length > 0 ? `?${params.join("&")}` : ""}`,
    })
    try {
        await liquibase.update({})
    } catch (err) {
        console.log("Liquibase failed")
        console.log(err)
    }
}

migrate().catch((err) => {
    console.log("Main thread failed", err)
})