import { inspect } from 'util'
import type { LogEntry } from '../lib/ws-message'

export function createLogger(sendMessage: (msg: LogEntry) => void) {
	const enableConsole = !!process.env.PRINT_CONSOLE
	return {
		log: (...args: any[]) => {
			if (enableConsole) console.log(...args)
			sendMessage({ message: prettyArgs(args), severity: 'INFO' })
		},
		debug: (...args: any[]) => {
			if (enableConsole) console.debug(...args)
			sendMessage({ message: prettyArgs(args), severity: 'DEBUG' })
		},
		error: (...args: any[]) => {
			if (enableConsole) console.error(...args)
			sendMessage({ message: prettyArgs(args), severity: 'ERROR' })
		},
		warn: (...args: any[]) => {
			if (enableConsole) console.warn(...args)
			sendMessage({ message: prettyArgs(args), severity: 'WARNING' })
		}
	}
}

function prettyArgs(args: any[]) {
	return args
		.map((arg) => (typeof arg === 'object' ? inspect(arg, { depth: null }) : arg))
		.join(' ')
}
