/**
 * Structured Smartcar OAuth + webhook breadcrumbs (grep `[Smartcar:Flow]`).
 * Verbose traces: set `SMARTCAR_DEBUG_LOG=1` (grep `[Smartcar:Debug]`).
 * Authorization `code` values are never logged verbatim.
 */

function redactValue(key: string, value: unknown): unknown {
  const k = key.toLowerCase();
  if (
    (typeof value === "string" && value.length > 10) &&
    (k.includes("code") || k.endsWith("_code") || k === "refreshtoken" || k === "accesstoken")
  ) {
    return `${value.slice(0, 6)}…(${value.length}ch)`;
  }
  return value;
}

export function scrubSmartcarFlowMeta(
  meta: Record<string, unknown>
): Record<string, unknown> {
  const out: Record<string, unknown> = {};
  for (const [key, val] of Object.entries(meta)) {
    if (Array.isArray(val))
      out[key] = val.map((v, i) => redactValue(`${key}.${i}`, v));
    else if (val && typeof val === "object" && !Array.isArray(val)) {
      out[key] = scrubSmartcarFlowMeta(val as Record<string, unknown>);
    } else {
      out[key] = redactValue(key, val);
    }
  }
  return out;
}

/** Default ON; set SMARTCAR_FLOW_LOG=0 to mute. */
export function smartcarFlowLogEnabled(): boolean {
  const raw = process.env.SMARTCAR_FLOW_LOG?.trim().toLowerCase();
  if (raw === "0" || raw === "false" || raw === "off") return false;
  if (process.env.NODE_ENV === "test" && raw !== "1" && raw !== "true" && raw !== "on")
    return false;
  return true;
}

/** Extra webhook / OAuth diagnostics. Opt-in: SMARTCAR_DEBUG_LOG=1 | true | on */
export function smartcarDebugLogEnabled(): boolean {
  const raw = process.env.SMARTCAR_DEBUG_LOG?.trim().toLowerCase();
  return raw === "1" || raw === "true" || raw === "on" || raw === "yes";
}

export function smartcarDebugLog(
  facet: string,
  msg: string,
  meta?: Record<string, unknown>
): void {
  if (!smartcarDebugLogEnabled()) return;
  const line =
    `[Smartcar:Debug:${facet}] ${msg}` +
    (meta && Object.keys(meta).length > 0
      ? ` ${JSON.stringify(scrubSmartcarFlowMeta(meta))}`
      : "");
  console.info(line);
}

export type SmartcarFlowFacet =
  | "redirect"
  | "callback"
  | "webhook_verify"
  | "webhook_delivery"
  | "oauth_login";

export function smartcarFlowLog(
  facet: SmartcarFlowFacet,
  msg: string,
  meta?: Record<string, unknown>
): void {
  if (!smartcarFlowLogEnabled()) return;
  const line =
    `[Smartcar:Flow:${facet}] ${msg}` +
    (meta && Object.keys(meta).length > 0
      ? ` ${JSON.stringify(scrubSmartcarFlowMeta(meta))}`
      : "");
  console.info(line);
}
