"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateMigrationFile = generateMigrationFile;
exports.buildFileContent = buildFileContent;
const tslib_1 = require("tslib");
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const fs_1 = require("fs");
const path_1 = tslib_1.__importDefault(require("path"));
const helpers_1 = require("../helpers");
const ddl_generator_1 = require("./ddl-generator");
function generateMigrationFile(statements, description) {
    const migrationsDir = (0, helpers_1.getSourceMigrationsDir)();
    if (!(0, fs_1.existsSync)(migrationsDir)) {
        (0, fs_1.mkdirSync)(migrationsDir, { recursive: true });
    }
    const timestamp = formatTimestamp(new Date());
    const slug = slugify(description);
    const filename = `${timestamp}_${slug}.ts`;
    const filePath = path_1.default.join(migrationsDir, filename);
    const content = buildFileContent(statements);
    (0, fs_1.writeFileSync)(filePath, content, 'utf8');
    return filePath;
}
generateMigrationFile.__type = ['statements', 'description', 'generateMigrationFile', 'P&F2!&2"&/#'];
function buildFileContent(statements) {
    const lines = [];
    let hasGroup = false;
    for (const stmt of statements) {
        if (stmt.startsWith(ddl_generator_1.COMMENT_PREFIX)) {
            const tableName = stmt.slice(ddl_generator_1.COMMENT_PREFIX.length);
            if (hasGroup)
                lines.push('');
            lines.push(`    // Table: ${tableName}`);
            hasGroup = true;
        }
        else {
            lines.push(formatStatement(stmt));
        }
    }
    const execLines = lines.join('\n');
    return `import { createMigration } from '@zyno-io/dk-server-foundation';\n\nexport default createMigration(async db => {\n${execLines}\n});\n`;
}
buildFileContent.__type = ['statements', 'buildFileContent', 'P&F2!&/"'];
function formatStatement(stmt) {
    const escaped = stmt.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$');
    if (!escaped.includes('\n')) {
        return `    await db.rawExecute(\`${escaped}\`);`;
    }
    const indented = escaped
        .split('\n')
        .map(__assignType(line => `        ${line}`, ['line', '', 'P"2!"/"']))
        .join('\n');
    return `    await db.rawExecute(\`\n${indented}\n    \`);`;
}
formatStatement.__type = ['stmt', 'formatStatement', 'P&2!&/"'];
function formatTimestamp(date) {
    const y = date.getUTCFullYear();
    const m = String(date.getUTCMonth() + 1).padStart(2, '0');
    const d = String(date.getUTCDate()).padStart(2, '0');
    const h = String(date.getUTCHours()).padStart(2, '0');
    const min = String(date.getUTCMinutes()).padStart(2, '0');
    const s = String(date.getUTCSeconds()).padStart(2, '0');
    return `${y}${m}${d}_${h}${min}${s}`;
}
formatTimestamp.__type = ['date', 'formatTimestamp', 'PT2!&/"'];
function slugify(text) {
    return text
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_|_$/g, '')
        .substring(0, 50);
}
slugify.__type = ['text', 'slugify', 'P&2!&/"'];
//# sourceMappingURL=file-generator.js.map