const express = require('express');
const nunjucks = require('nunjucks');
const path = require('path');
const jwt = require('jsonwebtoken');

const parser = require('cookie-parser');

const app = express();
const PORT = process.env.PORT;

const version = process.env.VERSION;
const vBuild = process.env.VERSION_BUILD;
const vState = process.env.VERSION_STATE;

app.use(express.json());
app.use(parser());

// Set up static files serving
const staticFolder = path.join(__dirname, 'static');
app.use('/static', express.static(staticFolder));

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

app.get('/health', (req, res) => {
    res.json({ 
        status: "ok",
        service: "console",
        version: version,
        build_number: vBuild,
        version_state: vState
    });
});

const pagesFolder = path.join(__dirname, 'pages');
nunjucks.configure(pagesFolder, {
    autoescape: true, 
    express: app,
    noCache: true,
    watch: false
})
app.set('views', pagesFolder);
app.set('view engine', 'html');

const renderPage = (page, extra = {}) => (req, res) => {
    res.render(page, {current_path: req.path, ...extra})
}

// Middleware di autenticazione per le pagine
app.use((req, res, next) => {
    if (req.path === '/health' || req.path.startsWith('/static')) {
        return next();
    }

    const authBase = process.env.AUTH_LOGIN_URL || 'http://localhost:3006/login';

    // Costruisci l'URL di redirect-back: protocollo + host + path originale
    const proto = req.protocol;
    const host = req.get('host');
    const redirectBack = `${proto}://${host}${req.originalUrl}`;
    const loginUrl = `${authBase}?redirect=${encodeURIComponent(redirectBack)}`;

    const token = req.cookies && req.cookies.auth_token;

    if (!token) {
        return res.redirect(loginUrl);
    }

    try {
        const payload = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
        req.user = payload;
        next();
    } catch (err) {
        const clearOptions = { httpOnly: true, sameSite: 'lax' };
        if (process.env.COOKIE_DOMAIN) {
            clearOptions.domain = process.env.COOKIE_DOMAIN;
        }
        res.clearCookie('auth_token', clearOptions);
        return res.redirect(loginUrl);
    }
});

app.get('/dashboard', renderPage('dashboard'));
app.get('/live', renderPage('live', {
    realtimeUrl: process.env.REALTIME_URL || 'http://localhost:3002',
    realtimeWsUrl: process.env.REALTIME_WS_URL || 'ws://localhost:3002'
}));

app.get('/rulesets', renderPage('rulesets', {
    apiUrl: process.env.API_URL || 'http://localhost:3003'
}));

app.get('/sessions', renderPage('sessions', {
    apiUrl: process.env.API_URL || 'http://localhost:3003',
    mapboxToken: process.env.MAPBOX_TOKEN || ''
}));

app.listen(PORT, '0.0.0.0', () => {
    console.log(`Started on port ${PORT}`);
});
