import pino from "pino";

// Single, simple Pino logger configuration
const isDev = process.env.NODE_ENV === "development";
const isBrowser = typeof window !== "undefined";

// Create one logger instance that works everywhere
export const logger = pino({
  level: process.env.LOG_LEVEL || "info",
  name: process.env.APP_NAME || "customer-portal",

  // Browser vs Node configuration
  ...(isBrowser
    ? {
        browser: {
          asObject: true,
          serialize: true,
        },
      }
    : {
        transport: isDev
          ? {
              target: "pino-pretty",
              options: {
                colorize: true,
                translateTime: "yyyy-mm-dd HH:MM:ss",
                ignore: "pid,hostname",
                messageFormat: "{msg}", // Cleaner message format
                hideObject: false, // Show structured data but cleaner
              },
            }
          : undefined,
      }),

  // Security: redact sensitive fields and reduce noise
  redact: {
    paths: [
      "req.headers.authorization",
      "req.headers.cookie",
      "req.body", // Hide request bodies
      "res.body", // Hide response bodies
      "password",
      "token",
      "secret",
      "jwt",
      "apiKey",
      "data", // Hide large data objects
    ],
    remove: true,
  },

  // Clean output format
  formatters: {
    level: (label: string) => ({ level: label }),
    bindings: () => ({}),
  },
});

// Export the same logger instance everywhere
export default logger;

// Helper functions for common logging patterns
export const log = {
  info: (message: string, data?: unknown) => logger.info(data, message),
  error: (message: string, error?: unknown) => logger.error(error, message),
  warn: (message: string, data?: unknown) => logger.warn(data, message),
  debug: (message: string, data?: unknown) => logger.debug(data, message),
};
