import { VAModel, LoggedModel } from "../../../models/vaModel.js"; // Getting all active VA's and their details async function va_callback(req, res) { try { // Find the latest log entry for each VA and return those whose last entry is LOGIN const agg = await LoggedModel.aggregate([ { $sort: { time: -1 } }, { $group: { _id: "$vaId", lastLog: { $first: "$$ROOT" } } }, { $match: { "lastLog.loggedType": "LOGIN" } } ]); const vaIds = agg.map((a) => a._id).filter(Boolean); if (vaIds.length === 0) { return res.status(200).json({ success: true, count: 0, data: [] }); } const vas = await VAModel.find({ _id: { $in: vaIds } }).lean().exec(); // map lastLog by VA id for easy attachment const lastLogByVa = agg.reduce((acc, a) => { acc[String(a._id)] = a.lastLog; return acc; }, {}); const results = vas.map((v) => ({ ...v, lastLog: lastLogByVa[String(v._id)] || null })); return res.status(200).json({ success: true, count: results.length, data: results }); } catch (error) { return res.status(500).send("Internal Server Error"); } } export { va_callback };