const { MongoClient } = require(‘mongodb’);

let cachedClient = null;

exports.handler = async (event) => {
const uri = process.env.MONGODB_URI;
const dbName = process.env.DB_NAME;
const collectionName = process.env.COLLECTION_NAME;

try {
    if (!cachedClient) {
        cachedClient = new MongoClient(uri);
        await cachedClient.connect();
        console.log("MongoDB client connected.");
    }

    const client = cachedClient;
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    console.log(`Connected to database: ${dbName}`);
    console.log(`Using collection: ${collectionName}`);
    
    // Perform the query and log the results
    const data = await collection.find({}).toArray();
    console.log("Query result:", JSON.stringify(data, null, 2));
    
    // Check if data is being retrieved correctly
    if (data && data.length > 0) {
        console.log(`Data retrieved: ${data.length} documents.`);
        return {
            statusCode: 200,
            body: JSON.stringify({ id: data._id }),
        };
    } else {
        console.warn("No data found in the collection.");
        return {
            statusCode: 404,
            body: JSON.stringify({ message: "No data found." }),
        };
    }
} catch (error) {
    console.error("Error querying MongoDB:", error);
    return {
        statusCode: 500,
        body: JSON.stringify({ error: "Internal Server Error" }),
    };
}

};