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

// 초기화된 pool을 export 하기 위한 변수
let pool = null;

const initPool = async () => {
  if (pool) return pool; // 이미 초기화된 경우 재사용

  await retry(async () => {
    pool = mysql.createPool({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT || 3306,
      user: process.env.DB_USER,
      password: process.env.DB_PASS,
      database: process.env.DB_NAME,
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0
    });

    const conn = await pool.getConnection();
    await conn.query('SET FOREIGN_KEY_CHECKS = 1');
    console.log(`✅ MariaDB 연결 성공: ${process.env.DB_HOST}:${process.env.DB_PORT || 3306}/${process.env.DB_NAME}`);
    conn.release();
  }, {
    retries: 10,
    minTimeout: 3000
  });

  return pool;
};

module.exports = initPool;