require('dotenv').config();
const express     = require('express');
const session     = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const path        = require('path');
const fs          = require('fs');

// Ensure data/ exists before anything tries to open a file inside it.
// connect-sqlite3 (sessions.db) and lib/db.js (training.db) both land here.
// On a fresh cPanel deploy the zip won't contain this folder, so we create it.
const DATA_DIR = path.join(__dirname, 'data');
fs.mkdirSync(DATA_DIR, { recursive: true });
const app         = express();

// ─── Session secret guard ─────────────────────────────────────────────────────
// In production SESSION_SECRET MUST be set explicitly — no insecure defaults.
const SESSION_SECRET = process.env.SESSION_SECRET;
if (!SESSION_SECRET) {
  if (process.env.NODE_ENV === 'production') {
    console.error('[FATAL] SESSION_SECRET environment variable is not set. Refusing to start in production without a session secret.');
    process.exit(1);
  } else {
    console.warn('[WARN] SESSION_SECRET is not set. Using an insecure default. Set SESSION_SECRET in your .env file before going to production.');
  }
}

// Trust the cPanel reverse proxy so sessions work correctly
app.set('trust proxy', 1);

// 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.urlencoded({ extended: true }));
app.use(express.json());
// Sessions stored in data/sessions.db — survives app restarts, safe for cPanel.
app.use(session({
  store: new SQLiteStore({
    db:  'sessions.db',
    dir: path.join(__dirname, 'data')
  }),
  secret:            SESSION_SECRET || 'ces-dev-only-change-before-production',
  resave:            false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    sameSite: 'lax',
    secure:   process.env.NODE_ENV === 'production',
    maxAge:   24 * 60 * 60 * 1000  // 24 hours
  }
}));

const db   = require('./lib/db');
const PORT = process.env.PORT || 3000;

(async () => {
  // Wait for all tables to be created before accepting any traffic.
  await db.init();

  // Seed reference data (idempotent)
  db.seedAgencies();

  // Routes
  app.use('/', require('./routes/learner'));
  app.use('/exam', require('./routes/exam'));
  app.use('/admin', require('./routes/admin'));

  // Error handler
  app.use((err, req, res, next) => {
    console.error(err);
    res.status(500).render('error', { message: err.message || 'Something went wrong.' });
  });

  app.listen(PORT, () => console.log(`CES Training running on port ${PORT}`));
})().catch(err => {
  console.error('[FATAL] Failed to initialize database:', err);
  process.exit(1);
});

module.exports = app;
