import { ConsoleLogger, Injectable, LogLevel } from '@nestjs/common'

import { yellow } from '@postxl/utils'

const DATETIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
})

const maxContextLength = 15

@Injectable()
export class CompactConsoleLogger extends ConsoleLogger {
  constructor(private readonly port: number) {
    super()
  }
  protected override formatMessage(
    logLevel: LogLevel,
    message: unknown,
    _pidMessage: string,
    formattedLogLevel: string,
    contextMessage: string,
    timestampDiff: string,
  ) {
    // Base logger will take care of stringification
    const output = this.stringifyMessage(message, logLevel) as string

    // pidMessage = this.colorize(pidMessage, logLevel)
    formattedLogLevel = logLevel === 'error' || logLevel === 'warn' ? this.colorize(formattedLogLevel, logLevel) : ''

    return `${this.getTimestamp()} ${contextMessage} ${formattedLogLevel}${output}${timestampDiff} ${contextMessage}\n`
  }

  protected override formatContext(context: string): string {
    if (context) {
      return yellow(`[${context.slice(0, maxContextLength)}]`.padEnd(maxContextLength + 2, ' '))
    }
    return ''.padEnd(maxContextLength, ' ')
  }

  protected override getTimestamp(): string {
    return DATETIME_FORMATTER.format(Date.now())
  }
}

function toMb(bytes: number): string {
  return `${(bytes / 1024 / 1024).toFixed(0)}m`
}

export function getMemoryUsage(): string {
  const { rss, heapUsed, heapTotal } = process.memoryUsage()
  const percent = Math.round((heapUsed / heapTotal) * 100)
  return `RSS:${toMb(rss)}/U:${toMb(heapUsed)}/T:${toMb(heapTotal)}/${percent}%`
}
