import {
    mysqlConfig,
} from '../config/dbConfig'
const mysql = require("mysql2");
const logger = require("../utils/log");

//创建连接池，添加错误处理和重试配置
const pool = mysql.createPool({
    ...mysqlConfig,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
    enableKeepAlive: true,
    keepAliveInitialDelay: 0,
    reconnect: true,
    // 连接池错误处理
    acquireTimeout: 60000,
});

// 监听连接池错误
pool.on('error', (err: any) => {
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        logger.error('MySQL连接丢失，正在尝试重连...', err);
    } else if (err.code === 'ECONNREFUSED') {
        logger.error(`MySQL连接被拒绝，请检查MySQL服务是否运行在 ${mysqlConfig.host}:${mysqlConfig.port}`, err);
    } else {
        logger.error('MySQL连接池错误:', err);
    }
});

const query = (sql, val) => {
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                logger.error('MySQL获取连接失败:', err);
                reject(err);
            } else {
                connection.query(sql, val, (err: any, fields: unknown) => {
                    if (err) {
                        logger.error('MySQL查询错误:', { sql, err });
                        reject(err);
                    } else {
                        resolve(fields);
                    }
                    connection.release();
                });
            }
        });
    });
};

export { query };
