"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MigrationResetCommand = void 0;
const tslib_1 = require("tslib");
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const app_1 = require("@deepkit/app");
const fs_1 = require("fs");
const path_1 = tslib_1.__importDefault(require("path"));
const resolver_1 = require("../../app/resolver");
const state_1 = require("../../app/state");
const services_1 = require("../../services");
const dialect_1 = require("../dialect");
const ddl_generator_1 = require("./create/ddl-generator");
const entity_reader_1 = require("./create/entity-reader");
const file_generator_1 = require("./create/file-generator");
const helpers_1 = require("./helpers");
let MigrationResetCommand = class MigrationResetCommand {
    constructor(dbProvider) {
        this.dbProvider = dbProvider;
        this.logger = (0, services_1.createLogger)('MigrationReset');
        this.migrationsDir = (0, helpers_1.getSourceMigrationsDir)();
    }
    async execute() {
        // Step 1: Ensure migrations directory exists
        if (!(0, fs_1.existsSync)(this.migrationsDir)) {
            this.logger.info(`Creating migrations directory: ${this.migrationsDir}`);
            (0, fs_1.mkdirSync)(this.migrationsDir, { recursive: true });
        }
        // Step 2: Remove all .ts files from migrations directory
        const files = (0, fs_1.readdirSync)(this.migrationsDir).filter(__assignType(f => f.endsWith('.ts'), ['f', '', 'P"2!"/"']));
        this.logger.info(`Removing ${files.length} migration file(s)`);
        for (const file of files) {
            const filePath = path_1.default.join(this.migrationsDir, file);
            (0, fs_1.unlinkSync)(filePath);
            this.logger.info(`Removed ${file}`);
        }
        // Step 3: Read entity schema from code definitions
        const db = this.dbProvider.db;
        const dialect = (0, dialect_1.getDialect)(db.adapter);
        const pgSchema = dialect === 'postgres' ? ((0, resolver_1.getAppConfig)().PG_SCHEMA ?? 'public') : 'public';
        this.logger.info('Reading entity definitions...');
        const entitySchema = (0, entity_reader_1.readEntitiesSchema)(db, dialect);
        const tables = Array.from(entitySchema.values());
        this.logger.info(`Found ${tables.length} entity table(s)`);
        // Step 4: Generate DDL by treating all entity tables as "added"
        const diff = {
            dialect,
            pgSchema: dialect === 'postgres' ? pgSchema : undefined,
            addedTables: tables,
            removedTables: [],
            modifiedTables: []
        };
        const statements = (0, ddl_generator_1.generateDDL)(diff);
        if (statements.length === 0) {
            this.logger.info('No tables found to generate base migration.');
            return;
        }
        // Step 6: Write migration file
        const migrationContent = (0, file_generator_1.buildFileContent)(statements);
        const migrationPath = path_1.default.join(this.migrationsDir, '00000000_000000_base.ts');
        (0, fs_1.writeFileSync)(migrationPath, migrationContent, 'utf8');
        this.logger.info(`Created initial migration: ${migrationPath}`);
        this.logger.info(`Migration reset complete with ${tables.length} table(s)`);
    }
};
exports.MigrationResetCommand = MigrationResetCommand;
MigrationResetCommand.__type = ['logger', function () { return (0, services_1.createLogger)('MigrationReset'); }, 'migrationsDir', function () { return (0, helpers_1.getSourceMigrationsDir)(); }, () => state_1.DBProvider, 'dbProvider', 'constructor', 'execute', 'MigrationResetCommand', '!3!;>"!3#;>$PP7%2&;"0\'P"0(5w)'];
exports.MigrationResetCommand = MigrationResetCommand = tslib_1.__decorate([
    app_1.cli.controller('migration:reset'),
    tslib_1.__metadata("design:paramtypes", [state_1.DBProvider])
], MigrationResetCommand);
//# sourceMappingURL=MigrationResetCommand.js.map