import "dotenv/config"
import mysql from "mysql2/promise"

async function main() {
  const url = process.env.DATABASE_URL
  if (!url) {
    console.error("DATABASE_URL not set")
    process.exit(1)
  }

  // Connect without specifying a database
  const urlObj = new URL(url)
  const dbName = urlObj.pathname.replace("/", "")
  const conn = await mysql.createConnection({
    host: urlObj.hostname,
    port: Number(urlObj.port),
    user: urlObj.username,
    password: decodeURIComponent(urlObj.password),
  })

  try {
    await conn.execute(
      `CREATE DATABASE IF NOT EXISTS \`${dbName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`
    )
    console.log(`Database '${dbName}' created (or already exists)`)
  } finally {
    await conn.end()
  }
}

main().catch((e) => {
  console.error(e)
  process.exit(1)
})
