/**
 * Client-side logging utility
 *
 * Provides structured logging with appropriate levels
 * and optional integration with error tracking services.
 */

interface LogMeta {
  [key: string]: unknown;
}

const formatMeta = (meta?: LogMeta): LogMeta | undefined => {
  if (meta && typeof meta === "object") {
    return meta;
  }
  return undefined;
};

class Logger {
  private readonly isDevelopment = process.env.NODE_ENV === "development";

  debug(message: string, meta?: LogMeta): void {
    if (this.isDevelopment) {
      console.debug(`[DEBUG] ${message}`, formatMeta(meta));
    }
  }

  info(message: string, meta?: LogMeta): void {
    if (this.isDevelopment) {
      console.info(`[INFO] ${message}`, formatMeta(meta));
    }
  }

  warn(message: string, meta?: LogMeta): void {
    console.warn(`[WARN] ${message}`, formatMeta(meta));
    // Integration point: Add monitoring service (e.g., Datadog, New Relic) for production warnings
  }

  error(message: string, error?: unknown, meta?: LogMeta): void {
    console.error(`[ERROR] ${message}`, error ?? "", formatMeta(meta));
    // Integration point: Add error tracking service (e.g., Sentry, Bugsnag) for production errors
    this.reportError(message, error, meta);
  }

  private reportError(message: string, error?: unknown, meta?: LogMeta): void {
    if (this.isDevelopment || typeof window === "undefined") {
      return;
    }

    // Placeholder for error tracking integration (e.g., Sentry, Datadog).
    // Keep payload available for future wiring instead of dropping context.
    const payload = { message, error, meta };
    void payload;
  }

  /**
   * Log API errors with additional context
   */
  apiError(endpoint: string, error: unknown, meta?: LogMeta): void {
    this.error(`API Error: ${endpoint}`, error, {
      endpoint,
      ...meta,
    });
  }

  /**
   * Log performance metrics
   */
  performance(metric: string, duration: number, meta?: LogMeta): void {
    if (this.isDevelopment) {
      console.info(`[PERF] ${metric}: ${duration}ms`, formatMeta(meta));
    }
  }
}

export const logger = new Logger();

export const log = {
  info: (message: string, meta?: LogMeta) => logger.info(message, meta),
  warn: (message: string, meta?: LogMeta) => logger.warn(message, meta),
  error: (message: string, error?: unknown, meta?: LogMeta) => logger.error(message, error, meta),
  debug: (message: string, meta?: LogMeta) => logger.debug(message, meta),
};
