/**
 * Pino Logger Configuration
 * Pretty printing in development, JSON in production
 */

import pino from 'pino';

const isDevelopment = process.env.NODE_ENV !== 'production';

export const logger = pino({
  level: process.env.LOG_LEVEL || (isDevelopment ? 'debug' : 'info'),
  
  // Pretty print in development
  transport: isDevelopment
    ? {
        target: 'pino-pretty',
        options: {
          colorize: true,
          translateTime: 'HH:MM:ss.l',
          ignore: 'pid,hostname',
          singleLine: false,
        },
      }
    : undefined,

  // Base fields
  base: {
    service: 'a2p-autopilot',
    env: process.env.NODE_ENV || 'development',
  },

  // Redact sensitive fields
  redact: {
    paths: [
      'apiKey',
      'password',
      'token',
      'secret',
      'authorization',
      '*.apiKey',
      '*.password',
      '*.token',
      '*.secret',
      'req.headers.authorization',
      'res.headers["set-cookie"]',
    ],
    censor: '[REDACTED]',
  },

  // Serialize errors properly
  serializers: {
    error: pino.stdSerializers.err,
    req: pino.stdSerializers.req,
    res: pino.stdSerializers.res,
  },
});

/**
 * Create a child logger with additional context
 */
export function createLogger(context: Record<string, any>) {
  return logger.child(context);
}

/**
 * Log an API call with timing
 */
export function logApiCall(
  method: string,
  endpoint: string,
  durationMs: number,
  statusCode: number
) {
  logger.info({
    type: 'api_call',
    method,
    endpoint,
    durationMs,
    statusCode,
  });
}

/**
 * Log a Twilio API call for audit trail
 */
export function logTwilioCall(
  submissionId: string,
  stepName: string,
  durationMs: number,
  success: boolean,
  error?: string
) {
  logger.info({
    type: 'twilio_call',
    submissionId,
    stepName,
    durationMs,
    success,
    error,
  });
}
