require('dotenv').config();
const express = require('express');
const sql = require('mssql');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cors());

const API_KEY = process.env.API_KEY;

const config = {
    user: process.env.DB_USERNAME_SQLSRVTEST,
    password: process.env.DB_PASSWORD_SQLSRVTEST,
    server: process.env.DB_HOST_SQLSRVTEST,
    port: parseInt(process.env.DB_PORT_SQLSRVTEST, 10),
    database: process.env.DB_DATABASE_SQLSRVTEST,
    options: {
        encrypt: false,
        trustServerCertificate: true
    }
};

// Middleware per verificare l'API Key
app.use((req, res, next) => {
    const apiKey = req.headers['x-api-key'];
    if (apiKey !== API_KEY) {
        return res.status(403).json({ error: 'Accesso negato' });
    }
    next();
});

// Endpoint per eseguire query
app.post('/query', async (req, res) => {
    try {
        await sql.connect(config);
        const result = await sql.query(req.body.query);
        res.json(result.recordset);
    } catch (err) {
        res.status(500).json({ error: err.message });
    } finally {
        sql.close();
    }
});

const PORT = process.env.SERVER_PORT || 3000;
app.listen(PORT, () => console.log(`Server in ascolto sulla porta ${PORT}`));
