const fs = require('fs');
const path = require('path');
const DatabaseClient = require('./db');
const config = require('../../config/default');

async function migrate() {
  const db = new DatabaseClient(config.db);
  const migrationsDir = path.join(__dirname, '..', '..', 'db', 'migrations');
  const files = fs.readdirSync(migrationsDir).filter((name) => name.endsWith('.sql'));
  for (const file of files) {
    const payload = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
    await db.exec(payload);
  }
  await db.close();
}

if (require.main === module) {
  migrate()
    .then(() => console.log('migrations applied'))
    .catch((err) => {
      console.error('migration failed', err);
      process.exit(1);
    });
}

module.exports = migrate;
