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

export interface AppError extends Error {
  statusCode?: number;
  isOperational?: boolean;
}

export const errorHandler = (
  err: AppError,
  req: Request,
  res: Response
): void => {
  console.log('💥💥💥 MAXIMUM DEBUG ERROR HANDLER HIT 💥💥💥');
  console.log('💥 Error name:', err.name);
  console.log('💥 Error message:', err.message);
  console.log('💥 Error code:', (err as any).code);
  console.log('💥 Error type:', typeof err);
  console.log('💥 Error constructor:', err.constructor.name);
  console.log('💥 Error stack:', err.stack);
  console.log('💥 Request URL:', req.url);
  console.log('💥 Request method:', req.method);
  console.log('💥 Full error object:', JSON.stringify(err, Object.getOwnPropertyNames(err), 2));
  console.log('💥💥💥 END ERROR DEBUG 💥💥💥');

  let error = { ...err };
  error.message = err.message;

  // Log error
  logger.error('Error occurred:', {
    error: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
    userAgent: req.get('User-Agent'),
  });

  // Mongoose bad ObjectId
  if (err.name === 'CastError') {
    const message = 'Resource not found';
    error = { message, statusCode: 404 } as AppError;
  }

  // Mongoose duplicate key
  if (err.name === 'MongoError' && (err as any).code === 11000) {
    const message = 'Duplicate field value entered';
    error = { message, statusCode: 400 } as AppError;
  }

  // Mongoose validation error
  if (err.name === 'ValidationError') {
    const message = Object.values((err as any).errors).map((val: any) => val.message).join(', ');
    error = { message, statusCode: 400 } as AppError;
  }

  // JWT errors
  if (err.name === 'JsonWebTokenError') {
    const message = 'Invalid token';
    error = { message, statusCode: 401 } as AppError;
  }

  if (err.name === 'TokenExpiredError') {
    const message = 'Token expired';
    error = { message, statusCode: 401 } as AppError;
  }

  // Multer errors (check if multer is imported anywhere)
  if (err.name === 'MulterError' || (err as any).code === 'UNEXPECTED_END_OF_FORM') {
    console.log('🚨 MULTER ERROR CAUGHT:', err.message);
    const message = `File upload failed: ${err.message}`;
    error = { message, statusCode: 400 } as AppError;
  }

  // Default error
  const statusCode = error.statusCode || 500;
  const message = error.message || 'Server Error';

  res.status(statusCode).json({
    success: false,
    error: message,
    ...(process.env['NODE_ENV'] === 'development' && { stack: err.stack }),
  });
}; 