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

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

function emit(level: LogLevel, component: string, message: string, ctx?: LogContext): void {
  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");
