const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);

console.log('📋 Session.js - CONNECTION_URI:', process.env.CONNECTION_URI);

// Parse the connection URI to extract connection options
const uriString = process.env.CONNECTION_URI;
const uriUrl = new URL(uriString);

// Extract individual components
const baseUri = `${uriUrl.protocol}//${uriUrl.username}:${uriUrl.password}@${uriUrl.hostname}:${uriUrl.port}${uriUrl.pathname}`;
const replicaSet = uriUrl.searchParams.get('replicaSet');
const authSource = uriUrl.searchParams.get('authSource');

console.log('📋 Base URI:', baseUri);
console.log('📋 ReplicaSet:', replicaSet);
console.log('📋 AuthSource:', authSource);

// Build connection options with directConnection to bypass replica set discovery
const connectionOptions = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    directConnection: true, // Force direct connection to specified server
};

if (authSource) {
    connectionOptions.authSource = authSource;
}

const storeOptions = {
    uri: baseUri,
    collection: 'sessions',
    connectionOptions: connectionOptions,
};

console.log('📋 Store options:', JSON.stringify(storeOptions, null, 2));

const store = new MongoDBStore(storeOptions);
const sessionMiddleware = session({
    store: store,
    credentials: true,
    cookie: {
        httpOnly: false,
        secure: false,
    },
    secret: 'secret',
    saveUninitialized: true,
    resave: true,
    maxAge: 20000,
});

const wrap = expressMiddleware => (socket, next) => expressMiddleware(socket.request, {}, next);

module.exports = { sessionMiddleware, wrap };
