/**
 * Debug logging, gated by the build-time `__DEBUG__` flag.
 *
 * `__DEBUG__` is set by the Vite configs (`define`):
 * - `VITE_DEBUG=true|false` in the env forces the value;
 * - otherwise it is `true` when `ENV_TYPE` is `dev` or `local`, and `false` for every
 *   other environment (preprod, prod…), so a production build never logs debug output.
 *
 * Use {@link createLogger} instead of `console.debug` / `console.log` / `console.table`…
 * When the flag is off, every method is a no-op and Terser drops the dead branch.
 * `console.error` and `console.warn` are not routed through here: they stay always on.
 *
 * @module Debug
 */

declare const __DEBUG__: boolean;

/**
 * Whether debug logging is enabled in this build.
 * The `typeof` guard keeps Jest (which has no Vite `define`) working: it sees `false`.
 */
export const DEBUG: boolean = typeof __DEBUG__ !== "undefined" && __DEBUG__;

type LogFn = (...args: unknown[]) => void;

/** Console-like logger whose output is prefixed with `[lisio:<scope>]`. */
export interface DebugLogger {
  debug: LogFn;
  log: LogFn;
  info: LogFn;
  table: (data: unknown, columns?: string[]) => void;
  group: LogFn;
  groupCollapsed: LogFn;
  groupEnd: () => void;
  trace: LogFn;
}

const noop = (): void => undefined;

const SILENT_LOGGER: DebugLogger = {
  debug: noop,
  log: noop,
  info: noop,
  table: noop,
  group: noop,
  groupCollapsed: noop,
  groupEnd: noop,
  trace: noop,
};

/**
 * Creates a logger for a feature area. The methods are `console` methods bound with the
 * prefix, so devtools still links each line to the real call site.
 *
 * @param scope Short area name, e.g. `"messages"` → `[lisio:messages] …`.
 * @returns A silent logger when {@link DEBUG} is off.
 */
export function createLogger(scope: string): DebugLogger {
  if (!DEBUG) {
    return SILENT_LOGGER;
  }
  const prefix = `[lisio:${scope}]`;
  return {
    debug: console.debug.bind(console, prefix),
    log: console.log.bind(console, prefix),
    info: console.info.bind(console, prefix),
    table: console.table.bind(console),
    group: console.group.bind(console, prefix),
    groupCollapsed: console.groupCollapsed.bind(console, prefix),
    groupEnd: console.groupEnd.bind(console),
    trace: console.trace.bind(console, prefix),
  };
}
