const neo4j = require('neo4j-driver');

/**
 * Clear Neo4j data for Template Manager
 * Usage:
 *   node src/scripts/clear-neo4j.js --scope=namespace   // clear only TM namespace
 *   node src/scripts/clear-neo4j.js --scope=all         // clear entire DB (DANGEROUS)
 */

function parseArgs() {
  const args = process.argv.slice(2);
  const options = { scope: 'namespace' };
  for (const arg of args) {
    const [key, value] = arg.split('=');
    if (key === '--scope' && (value === 'namespace' || value === 'all')) {
      options.scope = value;
    }
  }
  return options;
}

async function clearNeo4j(scope) {
  const uri = process.env.CKG_NEO4J_URI || process.env.NEO4J_URI || 'bolt://localhost:7687';
  const user = process.env.CKG_NEO4J_USERNAME || process.env.NEO4J_USERNAME || 'neo4j';
  const password = process.env.CKG_NEO4J_PASSWORD || process.env.NEO4J_PASSWORD || 'password';

  const driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
  const session = driver.session();

  try {
    console.log(`🔌 Connecting to Neo4j at ${uri} as ${user}...`);
    await driver.verifyAuthentication();
    console.log('✅ Connected');

    if (scope === 'all') {
      console.log('🧨 Clearing ENTIRE Neo4j database (nodes + relationships)...');
      await session.run('MATCH (n) DETACH DELETE n');
      console.log('✅ Full database cleared');
    } else {
      const namespace = 'TM';
      console.log(`🧹 Clearing namespace '${namespace}' (nodes with label and rel types containing _${namespace})...`);
      await session.run(`MATCH (n) WHERE '${namespace}' IN labels(n) DETACH DELETE n`);
      console.log(`✅ Cleared nodes in namespace '${namespace}'`);
      // Relationships are removed by DETACH DELETE above; no separate rel cleanup needed
    }
  } catch (error) {
    console.error('❌ Failed to clear Neo4j:', error.message);
    process.exitCode = 1;
  } finally {
    await session.close();
    await driver.close();
    console.log('🔌 Connection closed');
  }
}

(async () => {
  const { scope } = parseArgs();
  console.log(`🧭 Scope: ${scope}`);
  await clearNeo4j(scope);
})();


