import { AsyncLocalStorage } from 'node:async_hooks';

import type { NextFunction, Request, Response } from 'express';

export type HttpRequestContext = {
  req: Request;
  res: Response;
};

const requestContextStorage = new AsyncLocalStorage<HttpRequestContext>();

export function tryGetHttpRequestContext(): HttpRequestContext | null {
  return requestContextStorage.getStore() ?? null;
}

export function getHttpRequestContext(): HttpRequestContext {
  const ctx = tryGetHttpRequestContext();
  if (!ctx) {
    throw new Error('HttpRequestContext is not available (missing requestContextMiddleware)');
  }
  return ctx;
}

export function requestContextMiddleware(req: Request, res: Response, next: NextFunction): void {
  requestContextStorage.run({ req, res }, next);
}