const fs = require('fs').promises;
const path = require('path');
const { getFormattedDateForLogFile } = require('../utils/dateHelper');

const logDirectory = path.join(__dirname, '../logs');

/**
 * Membaca dan memparsing log berdasarkan tanggal.
 * @param {string} dateString - Format YYYY-MM-DD
 * @returns {Array} Array log terurut dari terbaru ke lama
 */
exports.readLogsByDate = async (dateString) => {
  const files = [
    `application-${dateString}.log`,
    `error-${dateString}.log`,
    `exceptions-${dateString}.log`
  ];

  let allParsedLogs = [];

  for (const file of files) {
    const filePath = path.join(logDirectory, file);
    try {
      const content = await fs.readFile(filePath, 'utf8');
      const lines = content.trim().split('\n');
      const logs = lines.map(line => {
        try {
          if (line.trim() === '') return null;
          return JSON.parse(line);
        } catch (e) {
          console.error(`Error parsing line in ${file}:`, line, e.message);
          return null;
        }
      }).filter(Boolean);
      allParsedLogs.push(...logs);
    } catch (err) {
      console.warn(`File not found or unreadable: ${file} (${err.message})`);
    }
  }

  allParsedLogs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
  return allParsedLogs;
};
