// Error Handling Middleware

import { Request, Response, NextFunction } from 'express';
import { DbisError, ErrorCode, ApiResponse } from '@/shared/types';
import { logger } from '@/infrastructure/monitoring/logger';

export function errorHandler(
  err: Error | DbisError,
  req: Request,
  res: Response,
  next: NextFunction
): void {
  if (err instanceof DbisError) {
    const statusCode = getStatusCode(err.code);
    const response: ApiResponse = {
      success: false,
      error: {
        code: err.code,
        message: err.message,
        details: err.details,
      },
      timestamp: new Date(),
    };

    res.status(statusCode).json(response);
    return;
  }

  // Handle unknown errors
  logger.error('Unhandled error', {
    error: err.message,
    stack: err.stack,
    path: req.path,
    method: req.method,
  });

  const response: ApiResponse = {
    success: false,
    error: {
      code: ErrorCode.INTERNAL_ERROR,
      message: 'Internal server error',
    },
    timestamp: new Date(),
  };

  res.status(500).json(response);
}

function getStatusCode(errorCode: ErrorCode): number {
  switch (errorCode) {
    case ErrorCode.VALIDATION_ERROR:
      return 400;
    case ErrorCode.UNAUTHORIZED:
      return 401;
    case ErrorCode.FORBIDDEN:
      return 403;
    case ErrorCode.NOT_FOUND:
      return 404;
    case ErrorCode.X100:
    case ErrorCode.X220:
    case ErrorCode.X402:
    case ErrorCode.X760:
      return 400;
    case ErrorCode.INTERNAL_ERROR:
    default:
      return 500;
  }
}

