"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__tsfTypeAliases = void 0;
exports.buildMigrationFileContent = buildMigrationFileContent;
exports.writeMigrationFile = writeMigrationFile;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-reflection/type-metadata-runtime"));
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const ddl_generator_1 = require("./ddl-generator");
function buildMigrationFileContent(statements, packageName = '@zyno-io/ts-server-foundation') {
    const lines = [];
    for (const statement of statements) {
        if (statement.startsWith(ddl_generator_1.COMMENT_PREFIX)) {
            lines.push('');
            lines.push(`    // Table: ${statement.slice(ddl_generator_1.COMMENT_PREFIX.length)}`);
        }
        else {
            lines.push(formatStatement(statement));
        }
    }
    return `import { createMigration } from '${packageName}';\n\nexport default createMigration(async db => {${lines.join('\n')}\n});\n`;
}
function writeMigrationFile(statements, description, options = {}) {
    const migrationsDir = options.migrationsDir ?? (0, node_path_1.join)(process.cwd(), 'src', 'migrations');
    if (!(0, node_fs_1.existsSync)(migrationsDir))
        (0, node_fs_1.mkdirSync)(migrationsDir, { recursive: true });
    const filename = `${timestamp(options.now ?? new Date())}_${slugify(description)}.ts`;
    const path = (0, node_path_1.join)(migrationsDir, filename);
    (0, node_fs_1.writeFileSync)(path, buildMigrationFileContent(statements), 'utf8');
    return path;
}
function formatStatement(statement) {
    const escaped = statement.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
    if (!escaped.includes('\n'))
        return `    await db.rawExecute(\`${escaped}\`);`;
    return `    await db.rawExecute(\`\n${escaped
        .split('\n')
        .map(line => `        ${line}`)
        .join('\n')}\n    \`);`;
}
function timestamp(date) {
    const parts = [
        date.getUTCFullYear(),
        date.getUTCMonth() + 1,
        date.getUTCDate(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds()
    ].map((part, index) => (index === 0 ? String(part) : String(part).padStart(2, '0')));
    return `${parts[0]}${parts[1]}${parts[2]}_${parts[3]}${parts[4]}${parts[5]}`;
}
function slugify(description) {
    const slug = description
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_|_$/g, '')
        .slice(0, 50);
    return slug || 'migration';
}
exports.__tsfTypeAliases = _a.decodeCompactMetadataV1("[1,{\"MigrationFileOptions\":{\"kind\":18,\"typeName\":\"MigrationFileOptions\",\"types\":[{\"kind\":20,\"name\":\"migrationsDir\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"now\",\"type\":{\"kind\":12,\"types\":[{\"kind\":16,\"typeName\":\"Date\",\"classType\":{\"$tsf\":0}},{\"kind\":4}]},\"optional\":true}]}}]", [() => (typeof Date !== "undefined" ? Date : (typeof exports !== "undefined" ? exports.Date : undefined))]);
//# sourceMappingURL=file-generator.js.map