import { createPool } from 'mysql2'

const pool = createPool({
  host: process.env.DB_HOST as string,
  user: process.env.DB_USER as string,
  password: process.env.DB_PASSWORD as string,
  database: process.env.DB_DATABASE as string,
  port: Number(process.env.DB_PORT),
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
})

pool.getConnection((err, conn) => {
  if (err) console.log('Error connecting to db...')
  else console.log('Connected to db...!')
  conn.release()
})

const executeQuery = (query: string, arrParams: any[]) => {
  return new Promise((resolve, reject) => {
    try {
      pool.query(query, arrParams, (err, data) => {
        if (err) {
          console.log('🚀 ~ pool.query ~ err:', err)
          reject(err)
        }
        console.log('🚀 ~ pool.query ~ data:', data)
        resolve(data)
      })
    } catch (err) {
      console.log('🚀 ~ returnnewPromise ~ err:', err)
      reject(err)
    }
  })
}

export default executeQuery
