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

const direction = process.argv[2] || 'up';
const file =
  direction === 'down'
    ? path.join(__dirname, '..', 'migrations', 'query02_optimization_down.sql')
    : path.join(__dirname, '..', 'migrations', 'query02_optimization_up.sql');

const splitStatements = (sql) =>
  sql
    .split(/;\s*(?:\r?\n|$)/)
    .map((item) => item.trim())
    .filter(Boolean)
    .filter((item) => !item.startsWith('--') || item.split(/\r?\n/).some((line) => !line.trim().startsWith('--')));

const stripLeadingComments = (statement) =>
  statement
    .split(/\r?\n/)
    .filter((line) => !line.trim().startsWith('--'))
    .join('\n')
    .trim();

const main = async () => {
  const sql = fs.readFileSync(file, 'utf8');
  const statements = splitStatements(sql).map(stripLeadingComments).filter(Boolean);
  const client = await createClient();

  try {
    await client.query('SET statement_timeout = 0');
    for (const statement of statements) {
      const started = performance.now();
      process.stdout.write(`${statement.split(/\s+/).slice(0, 6).join(' ')} ... `);
      await client.query(statement);
      process.stdout.write(`${(performance.now() - started).toFixed(2)}ms\n`);
    }
  } finally {
    await client.end();
  }
};

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