import fs from 'fs';
import path from 'path';
import { pool } from './db.js';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const MIGRATIONS_DIR = path.join(__dirname, '../../backend/migrations');

async function runMigrations() {
    console.log('📦 Running migrations from:', MIGRATIONS_DIR);

    try {
        const files = fs.readdirSync(MIGRATIONS_DIR)
            .filter(f => f.endsWith('.sql'))
            .sort();

        for (const file of files) {
            console.log(`   ▶️  Executing ${file}...`);
            const sql = fs.readFileSync(path.join(MIGRATIONS_DIR, file), 'utf8');
            await pool.query(sql);
        }

        console.log('✅ All migrations executed successfully');
    } catch (error) {
        console.error('❌ Error running migrations:', error);
    } finally {
        await pool.end();
    }
}

runMigrations();
