import "dotenv/config"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { drizzle } from "drizzle-orm/node-postgres"
import { migrate } from "drizzle-orm/node-postgres/migrator"
import { Pool } from "pg"

import { loadSecrets, secrets } from "../src/utils/secrets"

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

async function run() {
    let connectionString = process.env.DATABASE_URL

    if (!connectionString) {
        await loadSecrets()
        connectionString = secrets.DATABASE_URL
    }

    if (!connectionString) {
        throw new Error("DATABASE_URL not configured")
    }

    const pool = new Pool({
        connectionString,
        max: 1,
    })

    try {
        const db = drizzle(pool)

        await migrate(db, {
            migrationsFolder: path.resolve(__dirname, "../db/migrations"),
        })

        console.log("✅ Drizzle-Migrationen erfolgreich angewendet")
    } finally {
        await pool.end()
    }
}

run().catch((err) => {
    console.error("❌ Migration fehlgeschlagen")
    console.error(err)
    process.exit(1)
})
