'use strict';

/**
 * logger.js — pino wrapper with default config.
 * Singleton logger; supports session-scoped child loggers.
 */

const pino = require('pino');

let _logger = null;

function getLogger() {
  if (!_logger) {
    // Get log level from env directly (avoid circular dep with config.js)
    const rawLevel = process.env.LOG_LEVEL;
    const validLevels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal', 'silent'];
    const level = rawLevel && validLevels.includes(rawLevel) ? rawLevel : 'info';
    _logger = pino({
      level,
      base: { pid: process.pid },
      timestamp: pino.stdTimeFunctions.isoTime,
    });
  }
  return _logger;
}

/**
 * Create a child logger scoped to a session.
 * @param {string} sessionKey
 * @returns {pino.Logger}
 */
function sessionLogger(sessionKey) {
  return getLogger().child({ sessionKey });
}

/**
 * Reset the logger singleton (for tests).
 */
function resetLogger() {
  _logger = null;
}

module.exports = { getLogger, sessionLogger, resetLogger };
