const fs = require('fs');
const path = require('path');
const { createClient, benchmarkDir } = require('./benchmark-lib');

const direction = process.argv[2] === 'down' ? 'down' : 'up';
const file = path.join(benchmarkDir, 'migrations', `optimization_${direction}.sql`);

const splitStatements = (sql) =>
  sql
    .replace(/^\s*--.*$/gm, '')
    .split(/;\s*(?:\r?\n|$)/)
    .map((item) => item.trim())
    .filter(Boolean);

const main = async () => {
  const sql = fs.readFileSync(file, 'utf8');
  const statements = splitStatements(sql);
  const client = await createClient();
  try {
    await client.query('SET statement_timeout = 0');
    for (const statement of statements) {
      const started = Date.now();
      console.log(`Ejecutando: ${statement.split(/\r?\n/)[0].slice(0, 120)}`);
      await client.query(statement);
      console.log(`OK en ${((Date.now() - started) / 1000).toFixed(2)}s`);
    }
  } finally {
    await client.end();
  }
};

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
