// Setup Script for CVE Dashboard — PostgreSQL
// Runs the db-schema.sql DDL against the Postgres instance configured in DATABASE_URL.
// Idempotent — safe to run multiple times.
//
// Usage: node backend/setup-postgres.js
//
// Requires DATABASE_URL in .env or environment.

require('dotenv').config({ path: require('path').join(__dirname, '.env') });

const fs = require('fs');
const path = require('path');
const pool = require('./db');

const SCHEMA_FILE = path.join(__dirname, 'db-schema.sql');

async function main() {
    console.log('🚀 CVE Dashboard — PostgreSQL Schema Setup\n');
    console.log('════════════════════════════════════════\n');

    try {
        // Verify connection
        const { rows } = await pool.query('SELECT version()');
        console.log(`✓ Connected to: ${rows[0].version.split(',')[0]}`);
        console.log(`  Database URL: ${process.env.DATABASE_URL.replace(/:[^:@]+@/, ':***@')}\n`);

        // Read and execute schema
        const schema = fs.readFileSync(SCHEMA_FILE, 'utf8');
        await pool.query(schema);
        console.log('✓ Schema created/verified (all tables and indexes)\n');

        // Verify table count
        const { rows: tables } = await pool.query(
            "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = 'public'"
        );
        console.log(`✓ ${tables[0].count} tables in database\n`);

        console.log('╔════════════════════════════════════════════════════════╗');
        console.log('║       POSTGRESQL SCHEMA SETUP COMPLETE                 ║');
        console.log('╚════════════════════════════════════════════════════════╝\n');
    } catch (err) {
        console.error('❌ Setup failed:', err.message);
        process.exit(1);
    } finally {
        await pool.end();
    }
}

main();
