const fs = require('fs');
const path = require('path');
const {
  createClient,
  ensureDir,
  explainSql,
  explainSummary,
  query02Dir,
  query02Sql,
  writeJson
} = require('./query02-lib');

const phase = process.argv[2] || 'after';

const main = async () => {
  ensureDir(query02Dir);
  const client = await createClient();
  try {
    if (process.env.QUERY02_FORCE_OLD_PLAN === '1') {
      await client.query('SET enable_indexscan = off');
      await client.query('SET enable_indexonlyscan = off');
      await client.query('SET enable_bitmapscan = off');
    }
    const result = await client.query(explainSql(query02Sql));
    const doc = result.rows[0]['QUERY PLAN'][0];
    writeJson(path.join(query02Dir, `explain_${phase}.json`), doc);
    writeJson(path.join(query02Dir, `explain_${phase}_summary.json`), explainSummary(doc));
    console.log(`saved ${path.join(query02Dir, `explain_${phase}.json`)}`);
  } finally {
    await client.end();
  }
};

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