type Level = 'debug' | 'info' | 'warn' | 'error';

const LEVELS: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };

const minLevel = LEVELS[(process.env.LOG_LEVEL as Level) ?? 'info'] ?? LEVELS.info;
const isProd   = process.env.NODE_ENV === 'production';

function log(level: Level, msg: string, ctx?: Record<string, unknown>): void {
  if (LEVELS[level] < minLevel) return;

  if (isProd) {
    process.stderr.write(JSON.stringify({ time: Date.now(), level, msg, ...ctx }) + '\n');
  } else {
    const prefix = `[${level.toUpperCase()}]`;
    const extra  = ctx ? ' ' + JSON.stringify(ctx) : '';
    // eslint-disable-next-line no-console
    console.error(`${prefix} ${msg}${extra}`);
  }
}

export const logger = {
  debug: (msg: string, ctx?: Record<string, unknown>) => log('debug', msg, ctx),
  info:  (msg: string, ctx?: Record<string, unknown>) => log('info',  msg, ctx),
  warn:  (msg: string, ctx?: Record<string, unknown>) => log('warn',  msg, ctx),
  error: (msg: string, ctx?: Record<string, unknown>) => log('error', msg, ctx),
};
