/**
 * config/session.js
 * express-session with SQLite store. 24h rolling, 7d absolute.
 *
 * Hardening:
 *  - httpOnly + sameSite=lax on mutating sessions
 *  - secure flag in production
 *  - rolling: true → expiry resets on every request
 *  - absolute cap via a custom hook in middleware/auth.js (we track
 *    session.absoluteExpires)
 *
 * In production, assertProductionEnv() refuses to boot when
 * SESSION_SECRET is missing, too short, or still the .env.example
 * placeholder. The fallback below is only reachable in dev — and
 * even there it's a loud obvious string so a misconfigured deploy
 * is caught the moment a request goes through.
 */

'use strict';

const session       = require('express-session');
const connectSqlite = require('connect-sqlite3');
const path          = require('path');
const sec           = require('./security');

const SQLiteStore = connectSqlite(session);
const sessionDir = process.env.SESSION_DB_DIR || path.join(__dirname, '..', 'data');

if (process.env.NODE_ENV === 'production' && !process.env.SESSION_SECRET) {
  // assertProductionEnv should have already exited, but be defensive.
  throw new Error('SESSION_SECRET is required in production (see config/assertProductionEnv.js)');
}

module.exports = {
  store: new SQLiteStore({
    db: 'sessions.sqlite',
    dir: sessionDir,
  }),
  name: sec.SESSION_COOKIE_NAME,
  secret: process.env.SESSION_SECRET || (process.env.NODE_ENV === 'production'
    ? (() => { throw new Error('SESSION_SECRET is required in production'); })()
    : 'dev-only-insecure-session-secret-DO-NOT-USE-IN-PROD'),
  resave: false,
  saveUninitialized: false,
  rolling: true,
  cookie: {
    httpOnly: true,
    secure:   sec.SESSION_COOKIE_SECURE,
    sameSite: 'lax',                          // strict would break the OAuth-style flow
    maxAge:   sec.SESSION_TTL_MS,
  },
};
