const mysql = require('mysql2/promise')
const config = require('../config')

let pool

function getPool() {
  if (!pool) {
    pool = mysql.createPool({
      host: config.db.host,
      port: config.db.port,
      user: config.db.user,
      password: config.db.password,
      database: config.db.database,
      waitForConnections: true,
      connectionLimit: parseInt(process.env.DB_POOL_SIZE, 10) || 10,
      namedPlaceholders: true,
      timezone: '+08:00'
    })
  }
  return pool
}

async function query(sql, params) {
  const [rows] = await getPool().execute(sql, params || {})
  return rows
}

async function one(sql, params) {
  const rows = await query(sql, params)
  return rows[0] || null
}

async function transaction(work) {
  const conn = await getPool().getConnection()
  try {
    await conn.beginTransaction()
    const result = await work(conn)
    await conn.commit()
    return result
  } catch (err) {
    await conn.rollback()
    throw err
  } finally {
    conn.release()
  }
}

function limitClause(pageSize, offset) {
  return ' LIMIT ' + Number(pageSize) + ' OFFSET ' + Number(offset)
}

module.exports = { getPool, query, one, transaction, limitClause }
