/**
 * Structured server-side logger.
 *
 * Emits JSON lines to stderr so they appear in container/process logs without
 * polluting stdout (which Node's HTTP layer uses for responses).
 *
 * Format mirrors Go's log/slog default JSON output:
 *   {"time":"…","level":"ERROR","msg":"…","context":"pocketbase",...extra}
 *
 * Usage:
 *   import { log } from '$lib/server/logger';
 *   log.error('pocketbase', 'auth failed', { status: 401, url });
 *   log.warn('minio', 'presign slow', { slug, n, ms: elapsed });
 *   log.info('auth', 'user registered', { username });
 */

type Level = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
type Extra = Record<string, unknown>;

function emit(level: Level, context: string, msg: string, extra?: Extra): void {
	const entry: Record<string, unknown> = {
		time: new Date().toISOString(),
		level,
		context,
		msg,
		...extra
	};
	// Write to stderr — never stdout
	process.stderr.write(JSON.stringify(entry) + '\n');
}

export const log = {
	debug: (context: string, msg: string, extra?: Extra) => emit('DEBUG', context, msg, extra),
	info:  (context: string, msg: string, extra?: Extra) => emit('INFO',  context, msg, extra),
	warn:  (context: string, msg: string, extra?: Extra) => emit('WARN',  context, msg, extra),
	error: (context: string, msg: string, extra?: Extra) => emit('ERROR', context, msg, extra),
};
