import mysql from 'mysql2/promise'

// Pools de conexión a las mismas BD MySQL que usaba Django (django_wow + acore_*).
// Se guardan en globalThis para no crear pools nuevos en cada hot-reload de dev.
const g = globalThis as unknown as { _nwPools?: Record<string, mysql.Pool> }
g._nwPools ??= {}

export function db(database: string): mysql.Pool {
  if (!g._nwPools![database]) {
    g._nwPools![database] = mysql.createPool({
      host: process.env.DB_HOST || '127.0.0.1',
      port: Number(process.env.DB_PORT || 3306),
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database,
      waitForConnections: true,
      connectionLimit: 5,
      namedPlaceholders: true,
    })
  }
  return g._nwPools![database]
}

export const DB = {
  default: process.env.DB_NAME_DEFAULT || 'django_wow',
  auth: process.env.DB_NAME_AUTH || 'acore_auth',
  characters: process.env.DB_NAME_CHARACTERS || 'acore_characters',
  world: process.env.DB_NAME_WORLD || 'acore_world',
  web: process.env.DB_NAME_WEB || 'acore_web',
}
