// backend/src/migrate.js
import 'dotenv/config';
import { readFileSync, readdirSync } from 'fs';
import { fileURLToPath } from 'url';
import path from 'path';
import pg from 'pg';

const { Pool } = pg;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_DIR = path.join(__dirname, '../migrations');

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function migrate() {
  console.log('Running migrations...\n');

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

  if (files.length === 0) {
    console.log('No migration files found.');
    await pool.end();
    return;
  }

  for (const file of files) {
    process.stdout.write(`-> ${file} ... `);
    const sql = readFileSync(path.join(MIGRATIONS_DIR, file), 'utf8');
    try {
      await pool.query(sql);
      console.log('OK');
    } catch (err) {
      if (err.message.includes('already exists') || err.message.includes('duplicate')) {
        console.log('(already applied)');
      } else {
        console.log('ERROR');
        console.error(`   ${err.message}`);
      }
    }
  }

  console.log('\nAll migrations processed.');
  await pool.end();
}

migrate().catch(err => {
  console.error('Migration runner failed:', err.message);
  process.exit(1);
});
