const express = require('express');
const crypto = require('crypto');
const app = express();

const db = require('./store/db')
const redis = require('./store/redis');
const wsHandler = require('./ws/handler');

app.use(express.json());

// CORS — consenti richieste dalla console e altri client browser
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === 'OPTIONS') return res.sendStatus(204);
    next();
});

// DATABASE POSTGRESQL

app.get('/', (req, res) => {
    res.redirect('/health');
});

app.get('/health', (req, res) => {

    const sensorsDB = db.checkConnection('sensors');
    const dataDB = db.checkConnection('data');

    res.json({ 
        status: 'ok',
        databases: {
            sensors: sensorsDB ? 'connected' : 'disconnected',
            data: dataDB ? 'connected' : 'disconnected'
        },
        redis: redis.checkRedis() ? 'connected' : 'disconnected',
        version: process.env.VERSION,
        build_number: process.env.VERSION_BUILD
    });
});

app.use('/connect', require('./routes/connect'));
app.use('/sensors', require('./routes/sensors'));
app.use('/sessions', require('./routes/sessions'));

const server = app.listen(3000, '0.0.0.0', () => {
    console.log(`Realtime started`);
});

wsHandler.setup(server);
