const { Pool } = require('pg');
require('dotenv').config();

const poolConfig = process.env.DATABASE_URL 
    ? { connectionString: process.env.DATABASE_URL }
    : {
        host: process.env.DB_HOST,
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        port: parseInt(process.env.DB_PORT || '5432', 10),
        ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false
    };

const pool = new Pool(poolConfig);

// Run migrations on startup
const runMigrations = async () => {
    try {
        await pool.query(`
            ALTER TABLE properties ADD COLUMN IF NOT EXISTS allow_contact BOOLEAN DEFAULT TRUE;
            ALTER TABLE leads ADD COLUMN IF NOT EXISTS pending_status VARCHAR(50) DEFAULT 'None';
            ALTER TABLE leads ADD COLUMN IF NOT EXISTS pending_remarks TEXT;
            UPDATE users SET role = 'super_admin' WHERE mobile = '9030295951';
        `);
        console.log('Database migrations completed: verified schema and super_admin status.');
    } catch (err) {
        console.error('Failed to run database migrations:', err.message);
    }
};

runMigrations();

module.exports = {
    query: (text, params) => pool.query(text, params),
    pool
};
