require('../config/loadEnv')();

async function main() {
  const { MongoClient } = require('mongodb');
  const uri = process.env.AISFOR_CHAIN_LEDGER_DB_URI || process.env.DATABASE_URL || process.env.MONGODB_URI || '';
  if (!uri) {
    console.error(JSON.stringify({ ok: false, error: 'DB_URI_MISSING' }, null, 2));
    process.exit(1);
  }

  const client = new MongoClient(uri, {
    serverSelectionTimeoutMS: Number(process.env.AISFOR_CHAIN_LEDGER_DB_TIMEOUT_MS || 3000)
  });

  try {
    await client.connect();
    const db = client.db();
    const admin = db.admin();
    const ping = await admin.ping();
    const collections = await db.listCollections({}, { nameOnly: true }).toArray();
    console.log(JSON.stringify({
      ok: true,
      backend: 'mongodb',
      dbName: db.databaseName,
      pingOk: ping && ping.ok === 1,
      collectionCount: collections.length,
      checkedAt: new Date().toISOString()
    }, null, 2));
  } finally {
    await client.close();
  }
}

main().catch((error) => {
  console.error(JSON.stringify({
    ok: false,
    error: error.code || error.name || 'DB_CONNECT_FAILED',
    message: error.message
  }, null, 2));
  process.exit(1);
});
