"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__tsfTypeAliases = exports.DEFAULT_MYSQL_COLLATION = exports.DEFAULT_MYSQL_CHARSET = void 0;
exports.resetMigrations = resetMigrations;
exports.standardizeDbCollation = standardizeDbCollation;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const sql_1 = require("../sql");
const create_1 = require("./create");
const file_generator_1 = require("./create/file-generator");
exports.DEFAULT_MYSQL_CHARSET = 'utf8mb4';
exports.DEFAULT_MYSQL_COLLATION = 'utf8mb4_0900_ai_ci';
async function resetMigrations(db, 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 removedFiles = (0, node_fs_1.readdirSync)(migrationsDir)
        .filter(file => file.endsWith('.ts'))
        .sort();
    for (const file of removedFiles)
        (0, node_fs_1.unlinkSync)((0, node_path_1.join)(migrationsDir, file));
    const tables = [...(0, create_1.readEntitiesSchema)(db).values()];
    if (!tables.length) {
        return { migrationsDir, removedFiles, tableCount: 0, statements: [] };
    }
    const diff = {
        dialect: db.driver.dialect,
        pgSchema: options.pgSchema,
        externalForeignKeyDrops: [],
        externalForeignKeyAdds: [],
        addedTables: tables,
        removedTables: [],
        modifiedTables: []
    };
    const statements = (0, create_1.generateDDL)(diff);
    const migrationPath = (0, node_path_1.join)(migrationsDir, '00000000_000000_base.ts');
    (0, node_fs_1.writeFileSync)(migrationPath, (0, file_generator_1.buildMigrationFileContent)(statements), 'utf8');
    return { migrationsDir, removedFiles, tableCount: tables.length, statements, migrationPath };
}
async function standardizeDbCollation(db, options = {}) {
    if (db.driver.dialect === 'postgres') {
        console.warn('Character set standardization is not applicable to PostgreSQL');
        return { skipped: true, tables: [] };
    }
    const charset = assertSafeMySQLCharsetName(options.charset ?? exports.DEFAULT_MYSQL_CHARSET, 'charset');
    const collation = assertSafeMySQLCharsetName(options.collation ?? exports.DEFAULT_MYSQL_COLLATION, 'collation');
    const dbNameRow = await db.rawFindOne((0, sql_1.sql) `SELECT DATABASE() AS ${sql_1.sql.identifier('databaseName')}`);
    const databaseName = String(dbNameRow?.databaseName ?? '');
    if (!databaseName)
        throw new Error('Could not determine current MySQL database');
    await db.rawExecute((0, sql_1.sql) `ALTER DATABASE ${sql_1.sql.identifier(databaseName)} CHARACTER SET = ${sql_1.sql.rawTrusted(charset)} COLLATE = ${sql_1.sql.rawTrusted(collation)}`);
    const tableRows = await db.rawFind((0, sql_1.sql) `SHOW TABLES`);
    const tables = tableRows.map(row => Object.values(row)[0]).filter((value) => typeof value === 'string' && value.length > 0);
    for (const table of tables) {
        await db.rawExecute((0, sql_1.sql) `ALTER TABLE ${sql_1.sql.identifier(table)} CONVERT TO CHARACTER SET ${sql_1.sql.rawTrusted(charset)} COLLATE ${sql_1.sql.rawTrusted(collation)}`);
    }
    return { skipped: false, databaseName, tables };
}
function assertSafeMySQLCharsetName(value, field) {
    if (!/^[A-Za-z0-9_]+$/.test(value))
        throw new Error(`Invalid MySQL ${field}: ${value}`);
    return value;
}
exports.__tsfTypeAliases = _a.decodeCompactMetadataV1("[1,{\"ResetMigrationsOptions\":{\"kind\":18,\"typeName\":\"ResetMigrationsOptions\",\"types\":[{\"kind\":20,\"name\":\"migrationsDir\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"pgSchema\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true}]},\"ResetMigrationsResult\":{\"kind\":18,\"typeName\":\"ResetMigrationsResult\",\"types\":[{\"kind\":20,\"name\":\"migrationsDir\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"removedFiles\",\"type\":{\"kind\":14,\"type\":{\"kind\":6}},\"optional\":false},{\"kind\":20,\"name\":\"tableCount\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"statements\",\"type\":{\"kind\":14,\"type\":{\"kind\":6}},\"optional\":false},{\"kind\":20,\"name\":\"migrationPath\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true}]},\"StandardizeDbCollationOptions\":{\"kind\":18,\"typeName\":\"StandardizeDbCollationOptions\",\"types\":[{\"kind\":20,\"name\":\"charset\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"collation\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true}]},\"StandardizeDbCollationResult\":{\"kind\":18,\"typeName\":\"StandardizeDbCollationResult\",\"types\":[{\"kind\":20,\"name\":\"skipped\",\"type\":{\"kind\":8},\"optional\":false},{\"kind\":20,\"name\":\"databaseName\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"tables\",\"type\":{\"kind\":14,\"type\":{\"kind\":6}},\"optional\":false}]}}]", []);
//# sourceMappingURL=maintenance.js.map