import { Logger, LoggerService } from '@nestjs/common';

export class CustomLogger extends Logger implements LoggerService {
  constructor(context?: string) {
    super(context || 'Logger');
  }

  info(message: string | object) {
    const timestamp = new Date().toISOString();
    const formattedMessage = this.formatMessage(message, 'LOG', timestamp);

    super.log(formattedMessage);
  }

  error(message: string | object, trace?: string) {
    const timestamp = new Date().toISOString();
    const formattedMessage = this.formatMessage(message, 'ERROR', timestamp);
    super.error(formattedMessage, trace);
  }

  warning(message: string | object) {
    const timestamp = new Date().toISOString();
    const formattedMessage = this.formatMessage(message, 'WARN', timestamp);
    super.warn(formattedMessage);
  }

  private writeToStderr(message: string | object, level: string) {
    const timestamp = new Date().toISOString();
    const formatted = this.formatMessage(message, level, timestamp);
    console.error(formatted); // <-- Important: use console.error
  }

  private formatMessage(
    message: string | object,
    level: string,
    timestamp: string,
  ): string {
    const messageString =
      typeof message === 'object' ? JSON.stringify(message, null, 2) : message;
    return `${timestamp} [${level}]: ${messageString}`;
  }
}

export const logger = new CustomLogger();
