/**
 * Structured JSON logging. pino is the boring, fast, Fastify-ecosystem choice.
 * No pretty printers, no transports: JSON lines to a writable destination.
 */
import pino, { type DestinationStream, type Logger } from 'pino';
import type { LogBroadcaster } from './log-broadcaster.js';
import { Writable } from 'stream';

const SERVICE_NAME = 'mercadodevida-backend';

export interface LoggerOptions {
  /** Log level; defaults to LOG_LEVEL env var or 'info'. */
  level?: string;
  /** Explicit destination stream (tests use an in-memory stream). */
  destination?: DestinationStream;
  /** Log broadcaster for SSE streaming (optional). */
  broadcaster?: LogBroadcaster;
}

/**
 * Creates a pino logger. If a broadcaster is provided, logs are also pushed
 * to all connected SSE clients via that broadcaster.
 */
export function createLogger(options: LoggerOptions = {}): Logger {
  const level = options.level ?? process.env.LOG_LEVEL ?? 'info';
  const settings = { level, base: { service: SERVICE_NAME } };

  if (options.broadcaster) {
    // Custom Node.js Writable stream that forwards each JSON line to the broadcaster
    const toBroadcaster = new Writable({
      write(chunk: Buffer, _encoding: string, callback: () => void) {
        options.broadcaster!.addEntry(chunk.toString().trim());
        callback();
      },
      autoDestroy: true,
    });
    return pino(settings, toBroadcaster);
  }

  if (options.destination) {
    return pino(settings, options.destination);
  }

  return pino(settings);
}

export type { Logger };
