// dbPool.js
require('dotenv').config();
const mysql = require('mysql2/promise');
const retry = require('async-retry');

let pool = null;

async function initPool() {
  if (pool) return pool;

  const {
    DB_HOST, DB_PORT, DB_USER,
    DB_PASSWORD, DB_NAME,
    DB_SOCKET, DB_CONN_LIMIT = '10'
  } = process.env;

  if (!DB_USER || !DB_PASSWORD || !DB_NAME) {
    throw new Error('필수 환경변수(DB_USER, DB_PASSWORD, DB_NAME)가 없습니다.');
  }
  if (!DB_SOCKET && !DB_HOST) {
    throw new Error('DB_SOCKET이 없으면 DB_HOST가 반드시 필요합니다.');
  }

  await retry(async () => {
    const config = {
      user: DB_USER,
      password: DB_PASSWORD,
      database: DB_NAME,
      waitForConnections: true,
      connectionLimit: parseInt(DB_CONN_LIMIT, 10),
      queueLimit: 0,
      charset: 'utf8mb4'
    };
    if (DB_SOCKET) {
      config.socketPath = DB_SOCKET;
    } else {
      config.host = DB_HOST;
      config.port = parseInt(DB_PORT, 10);
    }

    pool = mysql.createPool(config);

    // 첫 연결 검증
    const conn = await pool.getConnection();
    await conn.query('SET NAMES utf8mb4');
    conn.release();

    console.log(`✅ MariaDB 연결 성공: ${DB_SOCKET ? `socket=${DB_SOCKET}` : `${DB_HOST}:${DB_PORT}`}`);
  }, {
    retries: 5,
    factor: 2,
    minTimeout: 1000
  });

  return pool;
}

async function getDb() {
  return initPool();
}

module.exports = { getDb };