import { Request, Response, NextFunction } from 'express';
import logger from '../utils/logger';

export const errorHandlerMiddleware = (
  error: Error & { code?: string },
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  logger.error('Error occurred:', {
    error: error.message,
    stack: error.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
  });

  // Multer errors (e.g. LIMIT_FILE_SIZE, file filter) → 400
  if (error.code === 'LIMIT_FILE_SIZE') {
    res.status(400).json({
      success: false,
      message: 'File too large. Maximum size is 15MB.',
      timestamp: new Date(),
    });
    return;
  }
  if (error.message === 'Only PDF files are allowed' || (error as any).code === 'LIMIT_UNEXPECTED_FILE') {
    res.status(400).json({
      success: false,
      message: error.message || 'Invalid file type.',
      timestamp: new Date(),
    });
    return;
  }

  res.status(500).json({
    success: false,
    message: 'Internal Server Error',
    timestamp: new Date(),
  });
};

export const notFoundMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  logger.warn(`Route not found: ${req.method} ${req.originalUrl}`);
  res.status(404).json({
    success: false,
    message: `Route ${req.originalUrl} not found`,
    timestamp: new Date(),
  });
};

export const asyncHandler = (fn: Function) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
};