// DB pool for the bot's OWN tables (guild_config, mod_actions, warnings) —
// mirrors server/src/utils/db.js. The bot never reads/writes any table it
// doesn't own; site-owned tables (users, bot_config, etc.) are reached only
// through the internal API, never directly. Schema for these tables lives in
// server/db/schema.sql (same physical database, ensured by the main server on
// boot) — there's no separate migration tool to justify a second database for
// a single-guild v1 bot.
const mariadb = require('mariadb')

const pool = mariadb.createPool({
  host: process.env.DB_HOST || '127.0.0.1',
  port: Number(process.env.DB_PORT) || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'runic_gateway',
  connectionLimit: 5,
  insertIdAsNumber: true,
  bigIntAsNumber: true,
  decimalAsNumber: true,
  // The driver defaults to 'local' — silently serializing bound JS Date
  // params using the HOST MACHINE's local offset instead of the DB session's
  // timezone (discovered via temp_roles.expires_at coming back hours off in
  // dev, CDT vs the container's UTC). 'auto' negotiates the actual session
  // timezone so Date round-trips correctly regardless of host TZ.
  timezone: 'auto',
})

async function query(sql, params) {
  const conn = await pool.getConnection()
  try {
    return await conn.query(sql, params)
  } finally {
    conn.release()
  }
}

async function close() {
  await pool.end()
}

module.exports = { query, close }
