import { execSync, ExecSyncOptions } from "child_process";
import os from "os";
import connDbHandler from "../db/conn-db-handler";

export type ExportMariaDBDatabaseParam = {
    dbFullName: string;
    targetFilePath: string;
    mariadbUser?: string;
    mariadbHost?: string;
    mariadbPass?: string;
};

export default async function importMariadbDatabase({
    dbFullName,
    targetFilePath,
    mariadbHost,
    mariadbPass,
    mariadbUser,
}: ExportMariaDBDatabaseParam) {
    const mysqlPath = os.platform().match(/win/i)
        ? "'" +
          "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" +
          "'"
        : "mysql";

    const finalMariadbUser = mariadbUser || process.env.DSQL_DB_USERNAME;
    const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST;
    const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD;

    await connDbHandler(
        global.DSQL_DB_CONN,
        `CREATE DATABASE IF NOT EXISTS ${dbFullName}`
    );

    const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} < ${targetFilePath}`;

    let execSyncOptions: ExecSyncOptions = {
        encoding: "utf-8",
    };

    const importDb = execSync(cmd, execSyncOptions);

    return importDb;
}
