"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
const _PlatformTools = require("typeorm/platform/PlatformTools");
const _CommandUtils = require("typeorm/commands/CommandUtils");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _chalk = /*#__PURE__*/ _interop_require_default(require("chalk"));
const _StringUtils = require("typeorm/util/StringUtils");
const _sqlFormatter = require("@sqltools/formatter/lib/sqlFormatter");
const _readline = /*#__PURE__*/ _interop_require_wildcard(require("readline"));
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
function queryParams(parameters) {
    if (!parameters || !parameters.length) {
        return "";
    }
    return `, ${JSON.stringify(parameters)}`;
}
function getTemplate(name, timestamp, upSqls, downSqls) {
    const migrationName = `${(0, _StringUtils.camelCase)(name, true)}${timestamp}`;
    return `import { MigrationInterface, QueryRunner } from "typeorm";

export class ${migrationName} implements MigrationInterface {
    name = '${migrationName}'

    public async up(queryRunner: QueryRunner): Promise<void> {
${upSqls.join(`
`)}
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
${downSqls.join(`
`)}
    }

}
`;
}
function getJavascriptTemplate(name, timestamp, upSqls, downSqls) {
    const migrationName = `${(0, _StringUtils.camelCase)(name, true)}${timestamp}`;
    return `const { MigrationInterface, QueryRunner } = require("typeorm");

module.exports = class ${migrationName} {
    name = '${migrationName}'

    async up(queryRunner) {
${upSqls.join(`
`)}
    }

    async down(queryRunner) {
${downSqls.join(`
`)}
    }
}
`;
}
function prettifyQuery(query) {
    const formattedQuery = (0, _sqlFormatter.format)(query, {
        indent: "    "
    });
    return "\n" + formattedQuery.replace(/^/gm, "            ") + "\n        ";
}
async function confirm(question, hint) {
    const line = _readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    return new Promise((resolve)=>{
        line.question(question, (response)=>{
            line.close();
            resolve(response);
        });
        line.write(hint);
    });
}
async function main() {
    const timestamp = _CommandUtils.CommandUtils.getTimestamp(Date.now());
    const extension = ".ts";
    let dataSource = undefined;
    try {
        dataSource = await _CommandUtils.CommandUtils.loadDataSource(_path.default.resolve(process.cwd(), "dist/data-source.js"));
        dataSource.setOptions({
            synchronize: false,
            migrationsRun: false,
            dropSchema: false,
            logging: false
        });
        await dataSource.initialize();
        const hasPendingMigrations = await dataSource.showMigrations();
        if (hasPendingMigrations) {
            console.log(_chalk.default.yellow(`ATTENTION: you have pending migrations (${_chalk.default.blue(hasPendingMigrations)}). Running those first, before generating a new migration.`));
            await dataSource.runMigrations({
                transaction: "each"
            });
            console.log(_chalk.default.green(`Migrations successfully executed.`));
        }
        const upSqls = [], downSqls = [];
        try {
            const sqlInMemory = await dataSource.driver.createSchemaBuilder().log();
            if (true) {
                sqlInMemory.upQueries.forEach((upQuery)=>{
                    upQuery.query = prettifyQuery(upQuery.query);
                });
                sqlInMemory.downQueries.forEach((downQuery)=>{
                    downQuery.query = prettifyQuery(downQuery.query);
                });
            }
            sqlInMemory.upQueries.forEach((upQuery)=>{
                upSqls.push("        await queryRunner.query(`" + upQuery.query.replace(new RegExp("`", "g"), "\\`") + "`" + queryParams(upQuery.parameters) + ");");
            });
            sqlInMemory.downQueries.forEach((downQuery)=>{
                downSqls.push("        await queryRunner.query(`" + downQuery.query.replace(new RegExp("`", "g"), "\\`") + "`" + queryParams(downQuery.parameters) + ");");
            });
        } finally{
            await dataSource.destroy();
        }
        if (!upSqls.length) {
            console.log(_chalk.default.green(`No changes in database schema were found`));
            process.exit(0);
        }
        console.log(_chalk.default.green(`Migration ready to be saved...`));
        console.log(_chalk.default.blue(upSqls.map((s)=>s).join("\n")));
        let name;
        while(!name){
            name = (await confirm("Please provide a name for the migration: ", "Change"))?.trim();
            if (name) break;
            console.log(_chalk.default.red(`Name is required, try again`));
            process.exit(1);
        }
        const fullPath = _path.default.resolve(process.cwd(), `src/migrations/${name}`);
        const filename = timestamp + "-" + _path.default.basename(fullPath) + extension;
        const fileContent = false ? getJavascriptTemplate(_path.default.basename(fullPath), timestamp, upSqls, downSqls.reverse()) : getTemplate(_path.default.basename(fullPath), timestamp, upSqls, downSqls.reverse());
        const migrationFileName = _path.default.dirname(fullPath) + "/" + filename;
        await _CommandUtils.CommandUtils.createFile(migrationFileName, fileContent);
        console.log(_chalk.default.green(`Migration ${_chalk.default.blue(migrationFileName)} has been generated successfully.`));
    } catch (err) {
        _PlatformTools.PlatformTools.logCmdErr("Error during migration generation:", err);
        process.exit(1);
    }
}
let start = new Date().getTime();
main().then(()=>{
    let end = new Date().getTime();
    console.log("done", end - start, "ms");
    process.exit(0);
});

//# sourceMappingURL=typeorm-generate.js.map