const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);

// Fail fast instead of silently starting with insecure defaults.
if (!process.env.SESSION_SECRET) {
  throw new Error('SESSION_SECRET не задан — установите его в .env');
}
if (!process.env.DB_PASSWORD) {
  throw new Error('DB_PASSWORD не задан — установите его в .env');
}

const store = new MySQLStore({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'wa_tools',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'wa_tools',
  clearExpired: true,
  checkExpirationInterval: 900000,
  expiration: 86400000,
  createDatabaseTable: true,
});

module.exports = session({
  key: 'wa_dev_tools',
  secret: process.env.SESSION_SECRET,
  store,
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 86400000,
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
  },
});

module.exports.store = store;
