"""
Business Logic Exceptions

Exceptions for business rule violations.
"""

from typing import Any, Optional, Dict

from .base import NexaException


class BusinessException(NexaException):
    """Base exception for business logic errors."""

    message = "Business rule violation"
    code = "BUSINESS_ERROR"
    http_status = 422


class WorkflowException(BusinessException):
    """Raised when workflow rules are violated."""

    message = "Workflow error"
    code = "WORKFLOW_ERROR"

    def __init__(
        self,
        workflow_id: Optional[str] = None,
        current_state: Optional[str] = None,
        target_state: Optional[str] = None,
        **kwargs,
    ):
        details = {}
        if workflow_id:
            details["workflow_id"] = workflow_id
        if current_state:
            details["current_state"] = current_state
        if target_state:
            details["target_state"] = target_state
        super().__init__(details=details, **kwargs)


class TenantException(BusinessException):
    """Raised when tenant-related operations fail."""

    message = "Tenant operation failed"
    code = "TENANT_ERROR"

    def __init__(
        self,
        tenant_id: Optional[str] = None,
        reason: Optional[str] = None,
        **kwargs,
    ):
        details = {}
        if tenant_id:
            details["tenant_id"] = tenant_id
        if reason:
            details["reason"] = reason
        super().__init__(details=details, **kwargs)


class QuotaExceededException(BusinessException):
    """Raised when a quota limit is exceeded."""

    message = "Quota exceeded"
    code = "QUOTA_EXCEEDED"

    def __init__(
        self,
        quota_type: str,
        limit: int,
        current: int,
        **kwargs,
    ):
        message = f"{quota_type} quota exceeded: {current}/{limit}"
        details = {
            "quota_type": quota_type,
            "limit": limit,
            "current": current,
        }
        super().__init__(message=message, details=details, **kwargs)


class StateTransitionException(BusinessException):
    """Raised when an invalid state transition is attempted."""

    message = "Invalid state transition"
    code = "INVALID_STATE_TRANSITION"

    def __init__(
        self,
        current_state: str,
        target_state: str,
        allowed_states: Optional[list] = None,
        **kwargs,
    ):
        message = f"Cannot transition from '{current_state}' to '{target_state}'"
        details = {
            "current_state": current_state,
            "target_state": target_state,
        }
        if allowed_states:
            details["allowed_states"] = allowed_states
        super().__init__(message=message, details=details, **kwargs)


class DuplicateException(BusinessException):
    """Raised when a duplicate resource is detected."""

    message = "Duplicate resource"
    code = "DUPLICATE_RESOURCE"
    http_status = 409

    def __init__(
        self,
        resource: str,
        field: str,
        value: Any,
        **kwargs,
    ):
        message = f"{resource} with {field}='{value}' already exists"
        details = {
            "resource": resource,
            "field": field,
            "value": str(value),
        }
        super().__init__(message=message, details=details, **kwargs)
