const { Pool }  = require('pg');

const baseConfig = {
    user: process.env.DB_USER || 'meb',
    password: process.env.DB_PSW,
    host: process.env.DB_HOST || 'meb-postgres',
    port: process.env.DB_PORT || 5432,
    max: 10,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 5000,
};

const dbs = {
    data: { name: 'data' },
    sensors: { name: 'sensors' },
    kiosk: { name: 'kiosk' },
}

const pools = {};

function getPool(db) {
    const dbConfig = dbs[db];
    if (!dbConfig) throw new Error(`Database ${db} not configured`);
    if (!pools[db]) {
        pools[db] = new Pool({ ...baseConfig, database: dbConfig.name });
    }
    return pools[db];
}

async function checkConnection(db) {
    try {
        await getPool(db).query('SELECT NOW()');
        return true;
    } catch (err) {
        console.error(`Error connecting to ${db} database`, err.message);
        return false;
    }
}

async function query(db, text, params) {
    const pool = getPool(db);
    return pool.query(text, params);
}

async function init() {
    try {
        // Tabella sensori
        await query('sensors', `
            CREATE TABLE IF NOT EXISTS sensors (
                id SERIAL PRIMARY KEY,
                name VARCHAR(255) UNIQUE NOT NULL,
                code_hash TEXT NOT NULL,
                created_at TIMESTAMPTZ DEFAULT NOW()
            );
        `);

        // Tabella sessioni: mappa session_id (tag InfluxDB) a metadati custom
        await query('sensors', `
            CREATE TABLE IF NOT EXISTS sessiondataref (
                id SERIAL PRIMARY KEY,
                session_id VARCHAR(32) UNIQUE NOT NULL,
                sensor_name VARCHAR(255) NOT NULL,
                name VARCHAR(255),
                description TEXT,
                tags TEXT[] DEFAULT '{}',
                created_at TIMESTAMPTZ DEFAULT NOW(),
                disconnected_at TIMESTAMPTZ,
                updated_at TIMESTAMPTZ DEFAULT NOW()
            );
        `);

        console.log('[DB] Tabelle verificate (sensors, sessiondataref)');
    } catch (err) {
        console.error('[DB] Error creating tables:', err.message);
    }
}

init();

module.exports = { checkConnection, query };
