/**
 * Minimal centralized logger. A thin wrapper over `console` so all server-side
 * logging goes through one place (timestamp + level + optional structured
 * context) without pulling in a heavyweight logging dependency. Swap the
 * implementation here if a transport (file/JSON/external) is ever needed.
 */
type LogContext = Record<string, unknown>;

function emit(
  level: 'error' | 'warn' | 'info',
  message: string,
  context?: LogContext,
): void {
  const line = `${new Date().toISOString()} [${level.toUpperCase()}] ${message}`;
  const payload = context && Object.keys(context).length > 0 ? [context] : [];

  if (level === 'error') {
    console.error(line, ...payload);
  } else if (level === 'warn') {
    console.warn(line, ...payload);
  } else {
    console.log(line, ...payload);
  }
}

/** Serializes an unknown thrown value into a stable, loggable shape. */
function describeError(error: unknown): LogContext {
  if (error instanceof Error) {
    return { name: error.name, message: error.message, stack: error.stack };
  }
  return { error };
}

const logger = {
  error(message: string, error?: unknown, context?: LogContext): void {
    emit('error', message, {
      ...(error !== undefined ? describeError(error) : {}),
      ...context,
    });
  },
  warn(message: string, context?: LogContext): void {
    emit('warn', message, context);
  },
  info(message: string, context?: LogContext): void {
    emit('info', message, context);
  },
};

export default logger;
