const session = require('express-session');
const RedisStore = require('connect-redis').default;
const { getRedisClient } = require('./redis');
const config = require('./env');

/**
 * Create and configure session middleware with Redis store
 * @returns {Function} - Express session middleware
 */
function createSessionMiddleware() {
  const redisClient = getRedisClient();

  // Create Redis store
  const redisStore = new RedisStore({
    client: redisClient,
    prefix: 'sess:',
    ttl: 86400, // 24 hours in seconds
  });

  // Session configuration
  const sessionConfig = {
    store: redisStore,
    secret: config.jwt.secret,
    resave: false,
    saveUninitialized: false,
    name: 'sessionId',
    cookie: {
      secure: config.nodeEnv === 'production', // HTTPS only in production
      httpOnly: true,
      maxAge: 1000 * 60 * 60 * 24, // 24 hours
      sameSite: 'strict',
    },
  };

  return session(sessionConfig);
}

module.exports = {
  createSessionMiddleware,
};
