export type LogLevel = "debug" | "info" | "warn" | "error";

export interface LogContext {
  [key: string]: unknown;
}

const LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };

function resolveMinLevel(): LogLevel {
  const env = (process.env["LOG_LEVEL"] ?? "").toLowerCase();
  if (env === "debug" || env === "info" || env === "warn" || env === "error") return env;
  return "debug";
}

const minLevel: number = LEVEL_ORDER[resolveMinLevel()];

function emit(level: LogLevel, component: string, message: string, ctx?: LogContext): void {
  if (LEVEL_ORDER[level] < minLevel) return;

  const line: Record<string, unknown> = {
    timestamp: new Date().toISOString(),
    level,
    component,
    message,
    ...ctx,
  };
  const out = JSON.stringify(line);
  if (level === "error" || level === "warn") {
    console.error(out);
  } else {
    console.log(out);
  }
}

export function makeLogger(component: string) {
  return {
    debug: (message: string, ctx?: LogContext) => emit("debug", component, message, ctx),
    info:  (message: string, ctx?: LogContext) => emit("info",  component, message, ctx),
    warn:  (message: string, ctx?: LogContext) => emit("warn",  component, message, ctx),
    error: (message: string, ctx?: LogContext) => emit("error", component, message, ctx),
  };
}

export const rootLogger = makeLogger("server");
