// scripts/drop-db.js
const { Client } = require('pg');
require('dotenv').config();

async function dropDatabase() {
  const url = new URL(process.env.DATABASE_URL);
  const dbName = url.pathname.slice(1);

  // Conectarse a "postgres" (la DB por defecto)
  url.pathname = '/postgres';
  const client = new Client({ connectionString: url.toString() });

  try {
    await client.connect();

    const res = await client.query(
      `SELECT 1 FROM pg_database WHERE datname = $1`,
      [dbName]
    );

    if (res.rowCount === 0) {
      console.log(`ℹ️  La base de datos "${dbName}" no existe.`);
      return;
    }

    // Desconectar sesiones activas antes de borrar
    await client.query(`
      SELECT pg_terminate_backend(pid)
      FROM pg_stat_activity
      WHERE datname = $1 AND pid <> pg_backend_pid()
    `, [dbName]);

    await client.query(`DROP DATABASE "${dbName}"`);
    console.log(`🗑️  Base de datos "${dbName}" eliminada.`);

  } finally {
    await client.end();
  }
}

dropDatabase().catch(err => {
  console.error('Error:', err.message);
  process.exit(1);
});