/**
 * Frontend logger with configurable level (window.__DT_LOG_LEVEL).
 * Ported from webapp/js/logger.js.
 */

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

function getLogLevel(): string {
  if (typeof window === "undefined") return "info";
  const raw = (window as unknown as { __DT_LOG_LEVEL?: string }).__DT_LOG_LEVEL ?? "info";
  const level = String(raw).toLowerCase();
  return Object.hasOwn(LEVEL_ORDER, level) ? level : "info";
}

function shouldLog(messageLevel: string): boolean {
  const configured = getLogLevel();
  const configuredNum = LEVEL_ORDER[configured] ?? 1;
  const messageNum = LEVEL_ORDER[messageLevel] ?? 1;
  return messageNum >= configuredNum;
}

const PREFIX = "[DutyTeller]";

function logAt(level: string, args: unknown[]): void {
  if (!shouldLog(level)) return;
  const consoleMethod =
    level === "debug"
      ? console.debug
      : level === "info"
        ? console.info
        : level === "warn"
          ? console.warn
          : console.error;
  const prefix = `${PREFIX}[${level}]`;
  if (args.length === 0) {
    (consoleMethod as (a: string) => void)(prefix);
  } else if (args.length === 1) {
    (consoleMethod as (a: string, b: unknown) => void)(prefix, args[0]);
  } else {
    (consoleMethod as (a: string, ...b: unknown[]) => void)(prefix, ...args);
  }
}

export const logger = {
  debug(msg: unknown, ...args: unknown[]): void {
    logAt("debug", [msg, ...args]);
  },
  info(msg: unknown, ...args: unknown[]): void {
    logAt("info", [msg, ...args]);
  },
  warn(msg: unknown, ...args: unknown[]): void {
    logAt("warn", [msg, ...args]);
  },
  error(msg: unknown, ...args: unknown[]): void {
    logAt("error", [msg, ...args]);
  },
};
