"""
Refresh access token function - standalone.
"""

from datetime import datetime, timedelta
from typing import Dict, Any

from apexsaas.core.security.jwt import decode_token as _verify_jwt_token, create_access_token, create_refresh_token
from apexsaas.exceptions import ApexValidationError, ApexAuthError


async def refresh_access_token(
    refresh_token: str,
    jwt_secret: str,
    expires_in: int = 3600
) -> Dict[str, Any]:
    """
    Refresh access token using refresh token (async).
    
    Args:
        refresh_token: JWT refresh token
        jwt_secret: Secret key for JWT
        expires_in: New access token expiration in seconds (default: 3600)
    
    Returns:
        dict with new access token:
        {
            'access_token': str,
            'refresh_token': str,
            'token_type': 'Bearer',
            'expires_in': int
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexAuthError: If refresh token is invalid or expired
    """
    if not refresh_token:
        raise ApexValidationError("refresh_token is required")
    if not jwt_secret:
        raise ApexValidationError("jwt_secret is required")
    
    try:
        # Verify refresh token
        payload = _verify_jwt_token(refresh_token, secret_key=jwt_secret)
        
        # Create new access token
        new_token_data = {
            "sub": payload.get("sub"),
            "email": payload.get("email")
        }
        
        access_token = create_access_token(data=new_token_data, expires_delta=timedelta(seconds=expires_in), secret_key=jwt_secret)
        
        # Create new refresh token
        refresh_token_data = {
            "sub": payload.get("sub"),
            "email": payload.get("email")
        }
        new_refresh_token = create_refresh_token(data=refresh_token_data, secret_key=jwt_secret)
        
        return {
            'access_token': access_token,
            'refresh_token': new_refresh_token,
            'token_type': 'Bearer',
            'expires_in': expires_in
        }
    except Exception as e:
        raise ApexAuthError(f"Invalid or expired refresh token: {str(e)}")


def refresh_access_token_sync(
    refresh_token: str,
    jwt_secret: str,
    expires_in: int = 3600
) -> Dict[str, Any]:
    """Sync wrapper for refresh_access_token."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(refresh_access_token(
            refresh_token=refresh_token,
            jwt_secret=jwt_secret,
            expires_in=expires_in
        ))
    except Exception as e:
        raise ApexAuthError(f"Token refresh failed: {str(e)}")
