import { Request, Response, NextFunction } from 'express';
import { OperationDeadline } from '../resources/operationDeadline.js';

declare global {
  // eslint-disable-next-line @typescript-eslint/no-namespace
  namespace Express {
    interface Locals {
      /**
       * An AbortSignal instantiated with the X-Unito-Operation-Deadline header. This header contains the timestamp
       * after which Unito will consider the operation to be timed out. You can use this signal to abort any
       * operation that would exceed this time frame. It also carries `operationDeadline` (epoch ms).
       */
      deadline: OperationDeadline;
    }
  }
}

const OPERATION_DEADLINE_HEADER = 'X-Unito-Operation-Deadline';

function extractOperationDeadline(req: Request, res: Response, next: NextFunction) {
  res.locals.deadline = OperationDeadline.fromHeader(req.header(OPERATION_DEADLINE_HEADER));

  next();
}

export default extractOperationDeadline;
