const SENSITIVE_KEYS = [
  "accesstoken",
  "refreshtoken",
  "secret",
  "authorization",
  "password",
  "apikey",
  "openaiapikey",
];

function sanitize(obj: any): any {
  if (!obj || typeof obj !== "object") return obj;

  if (Array.isArray(obj)) {
    return obj.map(sanitize);
  }

  const cleaned: Record<string, any> = {};
  for (const [key, value] of Object.entries(obj)) {
    const lowerKey = key.toLowerCase();
    if (SENSITIVE_KEYS.some((s) => lowerKey.includes(s))) {
      cleaned[key] = "[REDACTED]";
    } else if (typeof value === "object") {
      cleaned[key] = sanitize(value);
    } else {
      cleaned[key] = value;
    }
  }
  return cleaned;
}

export const logger = {
  info(message: string, context?: Record<string, any>) {
    console.log(
      JSON.stringify({
        level: "info",
        timestamp: new Date().toISOString(),
        message,
        ...(context ? { context: sanitize(context) } : {}),
      })
    );
  },

  warn(message: string, context?: Record<string, any>) {
    console.warn(
      JSON.stringify({
        level: "warn",
        timestamp: new Date().toISOString(),
        message,
        ...(context ? { context: sanitize(context) } : {}),
      })
    );
  },

  error(message: string, error?: any, context?: Record<string, any>) {
    console.error(
      JSON.stringify({
        level: "error",
        timestamp: new Date().toISOString(),
        message,
        error: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : error,
        ...(context ? { context: sanitize(context) } : {}),
      })
    );
  },
};
