"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("reflect-metadata");
const typeorm_1 = require("typeorm");
const dotenv = require("dotenv");
const path = require("path");
const fs = require("fs");
async function runMigrations() {
    const MIGRATE = process.env.MIGRATE;
    if (MIGRATE !== 'true') {
        console.log('MIGRATE env var not set to "true". Skipping migrations.');
        process.exit(0);
    }
    const envFile = path.resolve(process.cwd(), `.env.${process.env.NODE_ENV || 'development'}`);
    const defaultEnvFile = path.resolve(process.cwd(), '.env');
    if (fs.existsSync(envFile)) {
        dotenv.config({ path: envFile });
    }
    else if (fs.existsSync(defaultEnvFile)) {
        dotenv.config({ path: defaultEnvFile });
    }
    const ssl = process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false;
    const dataSource = new typeorm_1.DataSource({
        type: 'postgres',
        host: process.env.DB_HOST || 'localhost',
        port: parseInt(process.env.DB_PORT || '5432', 10),
        username: process.env.DB_USERNAME || 'hbs_user',
        password: process.env.DB_PASSWORD || 'hbs_password',
        database: process.env.DB_NAME || 'hbs_db',
        entities: [path.resolve(__dirname, 'entities', '*.entity{.ts,.js}')],
        migrations: [path.resolve(__dirname, '..', 'migrations', '*.{.ts,.js}')],
        migrationsTableName: 'typeorm_migrations',
        ssl: ssl,
        logging: true,
    });
    try {
        await dataSource.initialize();
        console.log('Data Source initialized.');
        const pendingMigrations = await dataSource.showMigrations();
        if (!pendingMigrations) {
            console.log('No pending migrations.');
        }
        else {
            console.log('Running pending migrations...');
            await dataSource.runMigrations();
            console.log('Migrations completed successfully.');
        }
        await dataSource.destroy();
        process.exit(0);
    }
    catch (error) {
        console.error('Migration failed:', error);
        process.exit(1);
    }
}
runMigrations();
