# mlink-backend/src/utils/error_handlers.py
import logging
from flask import Flask, jsonify, request
from werkzeug.exceptions import HTTPException
from src.config.env_loader import env

class ErrorHandler:
    """에러 처리 클래스"""
    
    @staticmethod
    def register_error_handlers(app: Flask):
        """에러 핸들러 등록"""
        
        @app.errorhandler(400)
        def bad_request(error):
            return ErrorHandler._create_error_response(
                'BAD_REQUEST',
                '잘못된 요청입니다.',
                400,
                str(error)
            )
        
        @app.errorhandler(401)
        def unauthorized(error):
            return ErrorHandler._create_error_response(
                'UNAUTHORIZED',
                '인증이 필요합니다.',
                401,
                str(error)
            )
        
        @app.errorhandler(403)
        def forbidden(error):
            return ErrorHandler._create_error_response(
                'FORBIDDEN',
                '접근이 거부되었습니다.',
                403,
                str(error)
            )
        
        @app.errorhandler(404)
        def not_found(error):
            return ErrorHandler._create_error_response(
                'NOT_FOUND',
                '요청한 리소스를 찾을 수 없습니다.',
                404,
                str(error)
            )
        
        @app.errorhandler(429)
        def rate_limit_exceeded(error):
            return ErrorHandler._create_error_response(
                'RATE_LIMIT_EXCEEDED',
                '요청 한도를 초과했습니다. 잠시 후 다시 시도해주세요.',
                429,
                str(error)
            )
        
        @app.errorhandler(500)
        def internal_server_error(error):
            return ErrorHandler._create_error_response(
                'INTERNAL_SERVER_ERROR',
                '서버 내부 오류가 발생했습니다.',
                500,
                str(error)
            )
        
        @app.errorhandler(Exception)
        def handle_unexpected_error(error):
            logging.error(f"예상치 못한 오류 발생: {str(error)}", exc_info=True)
            return ErrorHandler._create_error_response(
                'UNEXPECTED_ERROR',
                '예상치 못한 오류가 발생했습니다.',
                500,
                str(error) if env.get('ENVIRONMENT') == 'development' else None
            )
    
    @staticmethod
    def _create_error_response(error_code: str, message: str, status_code: int, details: str = None):
        """에러 응답 생성"""
        response = {
            'success': False,
            'error': {
                'code': error_code,
                'message': message,
                'timestamp': datetime.now().isoformat(),
                'request_id': request.headers.get('X-Request-ID', 'unknown')
            }
        }
        
        if details and env.get('ENVIRONMENT') == 'development':
            response['error']['details'] = details
        
        return jsonify(response), status_code

# 커스텀 예외 클래스들
class MLinkError(Exception):
    """MLink 기본 예외 클래스"""
    def __init__(self, message: str, error_code: str = None, status_code: int = 500):
        self.message = message
        self.error_code = error_code or 'UNKNOWN_ERROR'
        self.status_code = status_code
        super().__init__(self.message)

class ValidationError(MLinkError):
    """유효성 검사 오류"""
    def __init__(self, message: str):
        super().__init__(message, 'VALIDATION_ERROR', 400)

class AuthenticationError(MLinkError):
    """인증 오류"""
    def __init__(self, message: str):
        super().__init__(message, 'AUTHENTICATION_ERROR', 401)

class AuthorizationError(MLinkError):
    """권한 오류"""
    def __init__(self, message: str):
        super().__init__(message, 'AUTHORIZATION_ERROR', 403)

class ResourceNotFoundError(MLinkError):
    """리소스 없음 오류"""
    def __init__(self, message: str):
        super().__init__(message, 'RESOURCE_NOT_FOUND', 404)

class ExternalAPIError(MLinkError):
    """외부 API 오류"""
    def __init__(self, message: str, service: str = None):
        super().__init__(message, 'EXTERNAL_API_ERROR', 502)
        self.service = service