import { Request, Response, NextFunction } from 'express';
import Logger from '../resources/logger.js';

declare global {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace Express {
    interface Locals {
      logger: Logger;
      correlationId: string;
    }
  }
}

const ADDITIONAL_CONTEXT_HEADER = 'X-Unito-Additional-Logging-Context';

function injectLogger(req: Request, res: Response, next: NextFunction) {
  const logger = new Logger({ correlation_id: res.locals.correlationId });

  res.locals.logger = logger;

  const rawAdditionalContext = req.header(ADDITIONAL_CONTEXT_HEADER);

  if (typeof rawAdditionalContext === 'string') {
    try {
      const additionalContext = JSON.parse(rawAdditionalContext);

      logger.decorate(additionalContext);
    } catch (error) {
      logger.warn(`Failed parsing header ${ADDITIONAL_CONTEXT_HEADER}: ${rawAdditionalContext}`);
    }
  }

  next();
}

export default injectLogger;
