require('dotenv').config();
const express    = require('express');
const session    = require('express-session');
const flash      = require('connect-flash');
const path       = require('path');

  const app = express();
  app.set('trust proxy', 1); // trust nginx/reverse proxy for req.secure + req.ip

  // ── View engine ──────────────────────────────────────────────────────────────
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// ── Middleware ────────────────────────────────────────────────────────────────
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));
const SQLiteStore = require('./lib/session-store');
app.use(session({
  store:             new SQLiteStore(),
  secret:            process.env.SESSION_SECRET || 'vianexu-dev-secret',
  resave:            false,
  saveUninitialized: false,
  cookie:            { maxAge: 7 * 24 * 60 * 60 * 1000 }
}));
app.use(flash());

// ── i18n ──────────────────────────────────────────────────────────────────────
const fs    = require('fs');
const LANGS = ['en', 'pt'];
const locales = {};
LANGS.forEach(l => { locales[l] = JSON.parse(fs.readFileSync(path.join(__dirname, `locales/${l}.json`), 'utf8')); });

// Inject lang + locale into every /:lang route
app.use('/:lang([a-z]{2})', (req, res, next) => {
  const lang = LANGS.includes(req.params.lang) ? req.params.lang : 'en';
  res.locals.lang  = lang;
  res.locals.t     = locales[lang];
  res.locals.user  = req.session.user || null;
  res.locals.flash = { success: req.flash('success'), error: req.flash('error') };
  next();
});

// ── Routes ────────────────────────────────────────────────────────────────────
app.use('/:lang([a-z]{2})',           require('./routes/main'));
app.use('/:lang([a-z]{2})',           require('./routes/auth'));
app.use('/:lang([a-z]{2})/dashboard', require('./routes/dashboard'));
app.use('/ig',                        require('./routes/ig'));
app.use('/google',                    require('./routes/google'));
app.use('/api',                       require('./routes/api'));

// Root → /en/
app.get('/', (req, res) => res.redirect('/en/'));

// ── Static: /apps/finances/ (serve ficheiros directamente, PHP tratado pelo Apache) ──
app.use('/apps/finances', require('express').static(path.join(__dirname, '..', 'apps', 'finances')));

// ── 404 ───────────────────────────────────────────────────────────────────────
app.use((req, res) => {
  res.status(404).render('error', {
    lang: 'en', t: locales.en, user: null, flash: {},
    code: 404, message: 'Page not found'
  });
});

// ── Start ─────────────────────────────────────────────────────────────────────
const PORT = process.env.PORT || 1234;
app.listen(PORT, () => console.log(`✓ Vianexu on http://localhost:${PORT}`));
