// Request Timeout Middleware
// Configurable timeouts per endpoint type

import { Request, Response, NextFunction } from 'express';
import { logger } from '@/infrastructure/monitoring/logger';

interface TimeoutConfig {
  default: number;
  [endpoint: string]: number;
}

const timeoutConfig: TimeoutConfig = {
  default: 30000, // 30 seconds default
  '/api/settlement': 60000, // 60 seconds for settlement
  '/api/fx': 45000, // 45 seconds for FX
  '/api/compliance': 90000, // 90 seconds for compliance checks
};

/**
 * Create timeout middleware
 */
export function createTimeoutMiddleware(timeoutMs?: number) {
  return (req: Request, res: Response, next: NextFunction): void => {
    const timeout = timeoutMs || getTimeoutForPath(req.path);

    const timeoutId = setTimeout(() => {
      if (!res.headersSent) {
        logger.warn('Request timeout', {
          path: req.path,
          method: req.method,
          timeout: `${timeout}ms`,
        });

        res.status(504).json({
          success: false,
          error: {
            code: 'TIMEOUT',
            message: 'Request timeout',
          },
          timestamp: new Date(),
        });
      }
    }, timeout);

    // Clear timeout when response is sent
    res.on('finish', () => {
      clearTimeout(timeoutId);
    });

    next();
  };
}

/**
 * Get timeout for a specific path
 */
function getTimeoutForPath(path: string): number {
  for (const [endpoint, timeout] of Object.entries(timeoutConfig)) {
    if (path.startsWith(endpoint)) {
      return timeout;
    }
  }
  return timeoutConfig.default;
}

/**
 * Default timeout middleware
 */
export const timeoutMiddleware = createTimeoutMiddleware();

