// src/utils/debugLogger.js
// Saves raw request and response JSON to the /logs folder
// Same pattern as: saveDebugXml(`AirCreateReq-${traceId}-${timestamp}.xml`, xml)

const fs   = require('fs');
const path = require('path');

// logs folder sits at project root (same level as src/)
const LOGS_DIR = path.join(__dirname, '../../logs');

// Ensure logs folder exists on startup
if (!fs.existsSync(LOGS_DIR)) {
  fs.mkdirSync(LOGS_DIR, { recursive: true });
  console.log(`[DebugLogger] Created logs folder at: ${LOGS_DIR}`);
}

/**
 * Save a JSON object to the logs folder.
 * @param {string} filename  - e.g. "LowFareReq-TraceID_123-20260506_143000.json"
 * @param {object} data      - the raw request or response object
 */
function saveDebugJson(filename, data) {
  try {
    const filePath = path.join(LOGS_DIR, filename);
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    console.log(`[DebugLogger] Saved: logs/${filename}`);
  } catch (err) {
    console.error(`[DebugLogger] Failed to save ${filename}:`, err.message);
  }
}

/**
 * Generate a timestamp string for filenames — e.g. "20260506_143000"
 */
function getTimestamp() {
  const now = new Date();
  const date = now.toISOString().slice(0, 10).replace(/-/g, '');   // 20260506
  const time = now.toTimeString().slice(0, 8).replace(/:/g, '');   // 143000
  return `${date}_${time}`;
}

module.exports = { saveDebugJson, getTimestamp };