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

const phase = process.argv[2] || 'after';
const outFile = path.join(query02Dir, 'validation.json');

const main = async () => {
  ensureDir(query02Dir);
  const current = fs.existsSync(outFile)
    ? JSON.parse(fs.readFileSync(outFile, 'utf8'))
    : {
        query: 'query_02',
        pages: [0, 25, 250000, 1000000],
        note: 'La validacion incluye source_uid solo como identificador; el contrato publico se compara con las columnas reales del endpoint.'
      };

  const client = await createClient();
  try {
    if (phase === 'before' && 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');
    }
    if (phase === 'before') {
      current.before = await capturePageSet(client, current.pages);
      delete current.after;
      delete current.comparison;
    } else {
      if (!current.before) {
        throw new Error('No existe captura before. Ejecute primero: node benchmarks/scripts/validate-query02.js before');
      }
      current.after = await capturePageSet(client, current.pages);
      current.comparison = compareCaptures(current.before, current.after);
    }
  } finally {
    await client.end();
  }

  writeJson(outFile, current);
  console.log(JSON.stringify(current.comparison || { beforeCaptured: Boolean(current.before) }, null, 2));
};

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