const { getFormattedDateForLogFile } = require('../utils/dateHelper');
const { readLogsByDate } = require('../services/logService');
const { logger } = require('nodejs-log-agent');

exports.getLogData = async (req, res) => {
  try {
    let date = new Date();
    let dateString = getFormattedDateForLogFile(date);

    if (req.query.date) {
      const parsed = new Date(req.query.date);
      if (!isNaN(parsed.getTime())) {
        date = parsed;
        dateString = req.query.date;
      } else {
        console.warn(`Invalid query date: ${req.query.date}, using today.`);
      }
    }

    const logs = await readLogsByDate(dateString);

    res.json({
      status: true,
      message: "Logs fetched successfully",
      data: logs
    });
  } catch (error) {
    logger.error("[Function-LOG] GET : ", { message: error.message, stack: error.stack, error });
    res.json({
      status: false,
      message: error.message,
      error
    });
  }
};
