import type { Logger, LogTransport } from "./types.js";
import { LoggerImpl } from "./logger-impl.js";
import { ConsoleTransport } from "./console-transport.js";
import { JsonLinesHttpTransport } from "./json-lines-transport.js";

let cached: Logger | undefined;

/**
 * Creates or returns the cached root logger. In development, uses
 * ConsoleTransport. In other envs, uses JsonLinesHttpTransport if
 * LOGS_ENDPOINT is set, otherwise falls back to console.
 */
export function createRootLogger(): Logger {
  if (cached) return cached;

  const env =
    typeof process !== "undefined" ? process.env["NODE_ENV"] ?? "development" : "development";
  const logsEndpoint =
    typeof process !== "undefined" ? process.env["LOGS_ENDPOINT"] : undefined;

  let transport: LogTransport;

  if (env === "development" || !logsEndpoint) {
    transport = new ConsoleTransport();
  } else {
    transport = new JsonLinesHttpTransport({
      endpoint: logsEndpoint,
      batchSize: 50,
      flushIntervalMs: 5000,
      maxBufferSize: 500,
    });
  }

  cached = new LoggerImpl(transport);
  return cached;
}

/** Test-only: clears the cached root logger. */
export function __resetRootLoggerForTests(): void {
  cached = undefined;
}
