"""
Logout function - standalone, no database required.
"""

from datetime import datetime, timezone
from typing import Dict, Any

from apexsaas.auth.verify_token import verify_token
from apexsaas.exceptions import ApexValidationError, ApexAuthError


async def logout(
    token: str,
    jwt_secret: str
) -> Dict[str, Any]:
    """
    Logout a user by verifying and invalidating their token (async).
    
    Note: This function verifies the token is valid before logout.
    In a production system, you should also maintain a token blacklist
    on the server side to prevent reuse of logged-out tokens.
    
    Args:
        token: JWT access token to invalidate
        jwt_secret: Secret key for JWT verification
    
    Returns:
        dict with logout status:
        {
            'success': bool,
            'message': str,
            'logged_out_at': str
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexAuthError: If token is invalid
    """
    if not token:
        raise ApexValidationError("Token is required")
    if not jwt_secret:
        raise ApexValidationError("jwt_secret is required")
    
    # Verify token is valid before logout
    try:
        await verify_token(token, jwt_secret)
        
        return {
            'success': True,
            'message': 'Logged out successfully',
            'logged_out_at': datetime.now(timezone.utc).isoformat()
        }
    except ApexAuthError:
        return {
            'success': False,
            'message': 'Invalid or expired token',
            'logged_out_at': datetime.now(timezone.utc).isoformat()
        }


def logout_sync(
    token: str,
    jwt_secret: str
) -> Dict[str, Any]:
    """Sync wrapper for logout."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(logout(
            token=token,
            jwt_secret=jwt_secret
        ))
    except Exception as e:
        raise ApexAuthError(f"Logout failed: {str(e)}")
