// Centralized pino logger.
//
// Fastify already uses pino under the hood, but we want one configured pino
// instance shared between Fastify (via `logger: <instance>` in `Fastify({...})`)
// and any non-request code path (background tasks, repositories called outside
// a request, scripts). Importing the same instance everywhere means uniform
// formatting, redaction, and log level — and gives us one place to change
// transport later.
//
// Env knobs:
//   LOG_LEVEL   — pino level (`fatal|error|warn|info|debug|trace|silent`).
//                 Default: `debug` in non-production, `info` in production.
//   NODE_ENV    — `production` flips the default level.
//
// Redaction:
//   We strip Authorization headers and a small allow-list of secret-shaped
//   field names (`password`, `token`, `secret`, common Azure/JWT keys) from
//   any logged object so that an accidental `req.log.info(req.body)` or
//   `logger.error({ err, config }, ...)` doesn't leak credentials.

import pino from 'pino';

const isProd = process.env.NODE_ENV === 'production';
const level = process.env.LOG_LEVEL ?? (isProd ? 'info' : 'debug');

// Field paths we never want in logs. Pino's redact uses fast-redact's
// dot-path syntax with `*` wildcards. Cover the common cases without trying
// to be exhaustive — this is a backstop, not the primary defense.
const redactPaths = [
  // Headers (Fastify request log shape)
  'req.headers.authorization',
  'req.headers.cookie',
  'request.headers.authorization',
  'request.headers.cookie',
  'headers.authorization',
  'headers.cookie',
  // Common secret-shaped keys at the top level of a logged object
  '*.password',
  '*.token',
  '*.refreshToken',
  '*.refresh_token',
  '*.accessToken',
  '*.access_token',
  '*.csrfToken',
  '*.csrf_token',
  '*.JWT_SECRET',
  '*.CSRF_SECRET',
  '*.ENCRYPTION_KEY',
  '*.COSMOS_KEY',
  '*.AZURE_CLIENT_SECRET',
];

export const logger = pino({
  level,
  redact: {
    paths: redactPaths,
    censor: '[REDACTED]',
  },
  // Stable, JSON to stdout in every environment. If you want pretty output
  // locally, pipe through `pino-pretty` from your shell — we deliberately
  // don't bundle it as a runtime dep.
  base: { service: 'devops-backend' },
  timestamp: pino.stdTimeFunctions.isoTime,
});

// Convenience: a child logger tagged with a module name. Use this in
// repositories / background workers so log lines carry their origin
// without having to repeat it in every call site.
//
//   const log = childLogger('deployments/orchestrator');
//   log.error({ err, deploymentId }, 'background work failed');
export function childLogger(module: string) {
  return logger.child({ module });
}
