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

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

from apexsaas.core.security.password import verify_password
from apexsaas.core.security.jwt import create_access_token, create_refresh_token
from apexsaas.exceptions import ApexValidationError, ApexAuthError


async def login(
    email: str,
    password: str,
    stored_password_hash: str,
    jwt_secret: str,
    expires_in: int = 3600,
    refresh_expires_in: int = 604800  # 7 days
) -> Dict[str, Any]:
    """
    Login a user (async).
    
    Args:
        email: User email address
        password: Plain text password
        stored_password_hash: Hashed password from database
        jwt_secret: Secret key for JWT
        expires_in: Access token expiration in seconds (default: 3600)
        refresh_expires_in: Refresh token expiration in seconds (default: 604800)
    
    Returns:
        dict with tokens and user info:
        {
            'access_token': str,
            'refresh_token': str,
            'token_type': 'Bearer',
            'expires_in': int,
            'user': {
                'email': str
            }
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexAuthError: If authentication fails
    """
    if not email or not isinstance(email, str):
        raise ApexValidationError("Email is required")
    if not password:
        raise ApexValidationError("Password is required")
    if not stored_password_hash:
        raise ApexValidationError("stored_password_hash is required")
    if not jwt_secret:
        raise ApexValidationError("jwt_secret is required")
    
    # Verify password
    if not verify_password(password, stored_password_hash):
        raise ApexAuthError("Invalid email or password")
    
    # Generate tokens
    token_data = {
        "sub": email,
        "email": email
    }
    
    access_token = create_access_token(data=token_data, expires_delta=timedelta(seconds=expires_in), secret_key=jwt_secret)
    refresh_token = create_refresh_token(data=token_data, secret_key=jwt_secret)
    
    return {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'token_type': 'Bearer',
        'expires_in': expires_in,
        'user': {
            'email': email
        }
    }


def login_sync(
    email: str,
    password: str,
    stored_password_hash: str,
    jwt_secret: str,
    expires_in: int = 3600,
    refresh_expires_in: int = 604800
) -> Dict[str, Any]:
    """Sync wrapper for login."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(login(
            email=email,
            password=password,
            stored_password_hash=stored_password_hash,
            jwt_secret=jwt_secret,
            expires_in=expires_in,
            refresh_expires_in=refresh_expires_in
        ))
    except Exception as e:
        raise ApexAuthError(f"Login failed: {str(e)}")
