/**
 * Logger utility with LOG_LEVEL filtering
 *
 * LOG_LEVEL options (minimum level to show):
 * - debug: Show all logs
 * - info: Show info, success, warn, error, audit (default)
 * - warn: Show warn, error, audit
 * - error: Show only errors and audit
 */

const LOG_LEVELS = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
};

const colors = {
  reset: '\x1b[0m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
  gray: '\x1b[90m',
};

const getTimestamp = () => {
  return new Date().toISOString();
};

const getMinLevel = () => {
  const level = process.env.LOG_LEVEL?.toLowerCase() || 'info';
  return LOG_LEVELS[level] ?? LOG_LEVELS.info;
};

const shouldLog = (level) => {
  return LOG_LEVELS[level] >= getMinLevel();
};

export const logger = {
  info: (message, ...args) => {
    if (!shouldLog('info')) return;
    console.log(
      `${colors.blue}[INFO]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
  },

  success: (message, ...args) => {
    if (!shouldLog('info')) return;
    console.log(
      `${colors.green}[SUCCESS]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
  },

  warn: (message, ...args) => {
    if (!shouldLog('warn')) return;
    console.warn(
      `${colors.yellow}[WARN]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
  },

  error: (message, error, ...args) => {
    if (!shouldLog('error')) return;
    console.error(
      `${colors.red}[ERROR]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
    if (error && process.env.NODE_ENV === 'development') {
      console.error(error);
    }
  },

  debug: (message, ...args) => {
    if (!shouldLog('debug')) return;
    console.log(
      `${colors.cyan}[DEBUG]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
  },

  audit: (message, ...args) => {
    // Audit logs always show regardless of level
    console.log(
      `${colors.magenta}[AUDIT]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`,
      ...args
    );
  },

  // HTTP request logger - only logs errors (4xx, 5xx) by default
  http: (message, statusCode) => {
    // Only log HTTP errors, or all if LOG_LEVEL=debug
    const isError = statusCode >= 400;
    if (isError || getMinLevel() === LOG_LEVELS.debug) {
      const color = isError ? colors.red : colors.gray;
      console.log(
        `${color}[HTTP]${colors.reset} ${colors.gray}${getTimestamp()}${colors.reset} ${message}`
      );
    }
  },
};
