"""统一异常定义"""
from typing import Optional, Dict, Any
from fastapi import HTTPException, status


class BusinessError(HTTPException):
    """业务异常基类"""

    def __init__(
        self,
        message: str,
        code: int = status.HTTP_400_BAD_REQUEST,
        error_code: Optional[str] = None,
        detail: Optional[Dict[str, Any]] = None,
    ):
        super().__init__(
            status_code=code,
            detail={
                "message": message,
                "error_code": error_code or f"ERR_{code}",
                "detail": detail,
            },
        )
        self.message = message
        self.code = code
        self.error_code = error_code


class BadRequestError(BusinessError):
    """400 错误请求"""

    def __init__(self, message: str = "错误的请求", **kwargs):
        super().__init__(message, status.HTTP_400_BAD_REQUEST, **kwargs)


class UnauthorizedError(BusinessError):
    """401 未授权"""

    def __init__(self, message: str = "未授权", **kwargs):
        super().__init__(message, status.HTTP_401_UNAUTHORIZED, **kwargs)


class ForbiddenError(BusinessError):
    """403 禁止访问"""

    def __init__(self, message: str = "禁止访问", **kwargs):
        super().__init__(message, status.HTTP_403_FORBIDDEN, **kwargs)


class NotFoundError(BusinessError):
    """404 未找到"""

    def __init__(self, message: str = "资源未找到", **kwargs):
        super().__init__(message, status.HTTP_404_NOT_FOUND, **kwargs)


class ConflictError(BusinessError):
    """409 冲突"""

    def __init__(self, message: str = "资源冲突", **kwargs):
        super().__init__(message, status.HTTP_409_CONFLICT, **kwargs)


class ValidationError(BusinessError):
    """422 验证错误"""

    def __init__(self, message: str = "验证失败", **kwargs):
        super().__init__(message, status.HTTP_422_UNPROCESSABLE_ENTITY, **kwargs)


class InternalServerError(BusinessError):
    """500 内部服务器错误"""

    def __init__(self, message: str = "内部服务器错误", **kwargs):
        super().__init__(message, status.HTTP_500_INTERNAL_SERVER_ERROR, **kwargs)


class InsufficientPermissionsError(ForbiddenError):
    """权限不足"""

    def __init__(self, message: str = "权限不足", **kwargs):
        super().__init__(message, error_code="INSUFFICIENT_PERMISSIONS", **kwargs)


class ExternalServiceError(BusinessError):
    """外部服务错误"""

    def __init__(self, message: str = "外部服务异常", **kwargs):
        super().__init__(message, status.HTTP_502_BAD_GATEWAY, error_code="EXTERNAL_SERVICE_ERROR", **kwargs)
