"""
Reset password function - standalone, no database required.
"""

from datetime import datetime
from typing import Dict, Any

from apexsaas.core.security.password import get_password_hash
from apexsaas.core.utils.tokens import verify_reset_token
from apexsaas.exceptions import ApexValidationError, ApexAuthError


async def reset_password(
    token: str,
    new_password: str,
    stored_token: str,
    token_expiry: str
) -> Dict[str, Any]:
    """
    Reset password with token (async).
    
    Args:
        token: Reset token from request
        new_password: New password (will be hashed)
        stored_token: Token stored in database
        token_expiry: Token expiry timestamp (ISO format)
    
    Returns:
        dict with new password hash:
        {
            'password_hash': str,
            'success': bool
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexAuthError: If token is invalid or expired
    """
    if not token:
        raise ApexValidationError("Token is required")
    if not new_password or len(new_password) < 8:
        raise ApexValidationError("Password must be at least 8 characters")
    if not stored_token:
        raise ApexValidationError("stored_token is required")
    if not token_expiry:
        raise ApexValidationError("token_expiry is required")
    
    # Verify token
    if not verify_reset_token(token, stored_token, token_expiry):
        raise ApexAuthError("Invalid or expired reset token")
    
    # Hash new password
    password_hash = get_password_hash(new_password)
    
    return {
        'password_hash': password_hash,
        'success': True
    }


def reset_password_sync(
    token: str,
    new_password: str,
    stored_token: str,
    token_expiry: str
) -> Dict[str, Any]:
    """Sync wrapper for reset_password."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(reset_password(
            token=token,
            new_password=new_password,
            stored_token=stored_token,
            token_expiry=token_expiry
        ))
    except Exception as e:
        raise ApexAuthError(f"Reset password failed: {str(e)}")
