const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const os = require('os');

const envPath = path.join(__dirname, '..', '.env');

function getHostInfo() {
    var hostname = os.hostname();
    var interfaces = os.networkInterfaces();
    var ips = [];
    for (var name in interfaces) {
        (interfaces[name] || []).forEach(function(iface) {
            if (iface.family === 'IPv4' && !iface.internal) ips.push(iface.address);
        });
    }
    return { hostname: hostname, ips: ips };
}

router.get('/status', function(req, res) {
    var exists = fs.existsSync(envPath);
    res.json({ ok: true, configured: exists });
});

router.post('/test-connection', async function(req, res) {
    var server = req.body.server;
    var port = parseInt(req.body.port) || 1433;
    var database = req.body.database || 'master';
    var authType = req.body.authType || 'windows';
    var user = req.body.user || '';
    var password = req.body.password || '';
    var encrypt = req.body.encrypt === true;

    if (!server) return res.json({ ok: false, error: 'El nombre del servidor es requerido' });

    try {
        var config = {
            server: server,
            port: port,
            database: database,
            options: {
                encrypt: encrypt,
                trustServerCertificate: true,
                connectTimeout: 5000,
                requestTimeout: 10000
            }
        };

        if (authType === 'sql' && user) {
            config.user = user;
            config.password = password;
        }

        console.log('[SETUP] Test connection:', server + ':' + port + ', auth=' + authType + (user ? ', user=' + user : ''));

        var sql = require('mssql');
        var pool = await sql.connect(config);
        var result = await pool.request().query('SELECT DB_NAME() AS db_name, @@VERSION AS version');
        var dbName = result.recordset[0].db_name;
        var version = (result.recordset[0].version || '').split('\n')[0].trim();

        // Get list of databases
        var dbsResult = await pool.request().query("SELECT name FROM sys.databases WHERE state=0 AND name NOT IN ('master','tempdb','model','msdb') ORDER BY name");
        var databases = dbsResult.recordset.map(function(r) { return r.name; });

        await pool.close();

        res.json({
            ok: true,
            message: 'Conexión exitosa a ' + server,
            database: dbName,
            version: version,
            databases: databases
        });
    } catch (err) {
        res.json({ ok: false, error: err.message });
    }
});

router.post('/save', function(req, res) {
    var server = req.body.server;
    var port = parseInt(req.body.port) || 1433;
    var database = req.body.database;
    var authType = req.body.authType || 'windows';
    var user = req.body.user || '';
    var password = req.body.password || '';
    var encrypt = req.body.encrypt === true;

    if (!server) return res.json({ ok: false, error: 'Servidor requerido' });
    if (!database) return res.json({ ok: false, error: 'Base de datos requerida' });
    if (authType === 'sql' && (!user || !password)) return res.json({ ok: false, error: 'Usuario y contraseña requeridos para autenticación SQL' });

    var envContent = '';
    envContent += 'DB_SERVER=' + server + '\n';
    envContent += 'DB_PORT=' + port + '\n';
    envContent += 'DB_NAME=' + database + '\n';
    envContent += 'DB_ENCRYPT=' + (encrypt ? 'true' : 'false') + '\n';
    envContent += 'PORT=3000\n';

    if (authType === 'sql') {
        envContent += 'DB_USER=' + user + '\n';
        envContent += 'DB_PASSWORD=' + password + '\n';
    }

    try {
        fs.writeFileSync(envPath, envContent, 'utf8');
        res.json({ ok: true, message: 'Configuración guardada. Ahora reinicia el servidor para aplicar los cambios.' });
    } catch (err) {
        res.json({ ok: false, error: 'Error al guardar: ' + err.message });
    }
});

router.post('/restart', function(req, res) {
    res.json({ ok: true, message: 'Reiniciando servidor...' });
    setTimeout(function() {
        process.exit(0);
    }, 500);
});

router.get('/info', function(req, res) {
    res.json({ ok: true, data: getHostInfo() });
});

module.exports = router;
