// src/utils/logger.js
//
// Structured logger: console + daily rotating file.
// Resolves the target directory via src/utils/logPath.js so every part of the
// codebase writes to the same place (configurable via LOG_DIR env var, default
// ./logs). See logPath.js for the reasoning.

import fs from 'node:fs';
import path from 'node:path';
import { getLogDir, ensureLogDir } from './logPath.js';

/**
 * Enhanced logger: console + daily file
 * @param {string} context - usually function name or component (e.g. 'webhook', 'cron', 'deviceStatus')
 * @param {string} message - the log content
 * @param {string} [level='info'] - info, warn, error (for color/future filtering)
 */
export function logger(context, message, level = 'info') {
  const now = new Date();
  const dateStr = now.toLocaleString('en-US', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  });

  const yearMonthDay = now.toISOString().slice(0, 10).replace(/-/g, ''); // YYYYMMDD
  const logDir = ensureLogDir();
  const logFile = path.join(logDir, `${yearMonthDay}.log`);

  const prefixes = {
    info:  '[INFO]',
    warn:  '[WARN]',
    error: '[ERROR]',
  };
  const prefix = prefixes[level] || '[INFO]';
  console.log(`${dateStr} ${prefix} ${context.padEnd(15)} | ${message}`);

  const fileLine = `${dateStr} ${prefix} ${context.padEnd(15)} | ${message}\n`;
  try {
    fs.appendFileSync(logFile, fileLine);
  } catch (err) {
    console.error(`Logger failed to write to ${logFile}: ${err.message}`);
  }
}

// Convenience shortcuts
export const info  = (context, msg) => logger(context, msg, 'info');
export const warn  = (context, msg) => logger(context, msg, 'warn');
export const error = (context, msg) => logger(context, msg, 'error');

// Re-export so callers that need the directory (webhook archiver, log cleaner)
// don't have to import logPath separately.
export { getLogDir, ensureLogDir };

export default logger;
