const fs = require('fs');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const mysql = require('mysql2');

async function createDatabase(host, username, password, dbname) {
    const { stdout, stderr } = await exec(`mysql -h ${host} -u${username} -p${password} -e "CREATE DATABASE IF NOT EXISTS ${dbname} CHARACTER SET utf8mb4"`);
    if (stderr) {
        if (!stderr.includes('Warning')) {
            throw new Error(`Error creating database: ${stderr}`);
        }
    }
    console.log(`Database created: ${stdout}`);
}

function executeSqlFile(connection, filePath) {
    return new Promise((resolve, reject) => {
        const sqlFileContent = fs.readFileSync(filePath, 'utf8');
        const sqlQueries = sqlFileContent.split(';');
        sqlQueries.pop(); // 去除数组末尾的空语句

        const executeNextQuery = (index) => {
            if (index >= sqlQueries.length) {
                resolve('All queries executed successfully.');
                return;
            }
            const query = sqlQueries[index];
            connection.query(query, (err, results) => {
                if (err) {
                    reject(`Error executing query at index ${index}: ${err}`);
                } else {
                    console.log(`Query at index ${index} executed successfully.`);
                    executeNextQuery(index + 1);
                }
            });
        };

        executeNextQuery(0);
    });
}
async function runSql(host, username, password, dbname, sqlfile) {
    let connection; // 声明连接变量在 try 块外部

    try {
        await createDatabase(host, username, password, dbname);

        connection = mysql.createConnection({
            host: host,
            user: username,
            password: password,
            database: dbname
        });

        await connection.promise().connect();
        await executeSqlFile(connection, sqlfile);
        console.log(`数据库${dbname}的sql执行完成`)
    } catch (error) {
        console.error('Error:', error);
        console.log(`初始化sql执行失败，请手动创建数据库：【${dbname}】并在该库下执行项目目录的init.sql文件`)
    } finally {
        
        if (connection) {
            connection.end();
        }
    }
}

module.exports = {
    runSql
}

